博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件上传
阅读量:7082 次
发布时间:2019-06-28

本文共 8453 字,大约阅读时间需要 28 分钟。

1.AjaxFileUpload

地址:

下载:

   js:

    Html:

   后台:

public void AjaxSave() {     var file = Request.Files[0];     string path = Server.MapPath("~") + "/Upfiles/" + "/";     if (!Directory.Exists(path))      {         Directory.CreateDirectory(path);      }      file.SaveAs(path + Path.GetFileName(file.FileName));}

 2.Ajax文件上传

    1.Index视图中添加一个上传控件,请求文件列表的js。

文件列表
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, htmlAttributes: new { enctype = "multipart/form-data", target = "msgframe" })) {
}

    2.控制器

public class HomeController : Controller    {        //Index        public ViewResult Index()        {            return View();        }        //上传        public ActionResult Upload()        {            //获取文件            var file = Request.Files["fileToUpload"];            string msg = "";            //保存            if (file != null && file.ContentLength > 0)            {                //文件目录                string path = Server.MapPath("~") + "Upfiles\\";                if (!Directory.Exists(path))                {                    Directory.CreateDirectory(path);                }                //文件类型验证                string[] allowExtension = { "application/x-bmp" ,"image/jpeg", "application/x-jpg", "image/gif", "application/x-png",                                             "application/msword","applications-powerpoint", "application/x-ppt", "application/-excel",                                             "application/x-xls","application/vnd.ms-excel" };                if (!allowExtension.Contains(file.ContentType))                {                    msg = "上传文件类型不正确";                }                else                {                    //上传文件大小验证                    long len = GetDirectoryLength(path) + file.ContentLength;                    if (len <= 10 * 1024 * 1024)                    {                        string directoryName = path + "\\" + file.FileName;                        file.SaveAs(directoryName);//文件                    }                    else                    {                        msg = "每个借款项目的文件不能超过10M";                    }                }            }            else            {                msg = "添加文件失败";            }            if (!string.IsNullOrEmpty(msg))            {                Response.Write("");            }            Response.Write("");            return View();        }        //判断目录下文件的总大小        private long GetDirectoryLength(string dirPath)        {            long len = 0;            DirectoryInfo di = new DirectoryInfo(dirPath);            foreach (FileInfo fi in di.GetFiles())            {                len += fi.Length;            }            foreach (DirectoryInfo dis in di.GetDirectories())            {                len += GetDirectoryLength(dis.FullName);            }            return len;        }        //文件列表        public ActionResult FileList()        {            return PartialView();        }    }

    3.Upload视图

@{    Layout = null;}    Upload    

 补充:

 

string strReturn =@"        ";                    context.Response.ContentType = "text/html";                    context.Response.Write(strReturn.Replace("@msg", msg));

 3.选中文件即上传

function upload() {        $("#fileToUpload").click();        setTimeout("checkFile()", 1000);    }    var timeout;    function checkFile() {        var filePath = $("#fileToUpload").val();        if (filePath == "" || filePath == null) {            timeout = setTimeout("checkFile()", 1000);        } else {            clearTimeout(timeout);            $("#formUpload").submit();            $("#fileToUpload").val("");        }    }

 

Request.File文件大小限制

错误消息:超过了最大请求长度

 
错误原因:asp.net默认最大上传文件大小为4M,运行超时时间为90S。
 
解决方案:
 
1. 修改web.config文件可以改变这个默认值     
   
<configuration>     
      <system.web>   
                  <httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
      </system.web>   
<configuration> 
 
2.另一种方法是修改.NET FrameWork:
 
(1) 修改 C:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/CONFIG  目录下的machine.config 文件。
 
(2) 查找    "<httpruntime"    在这一行将  maxRequestLength的值改为理想的值,比如想要8M,就输入8192.     
这样,你的任何一个    web    工程都可以上传最大8M的文件。
3.顺便说下IIS中限制上传文件大小的修改方法:
 
(1)首先要到进程中把IIS服务关了,即把inetinfo.exe进程关了。
 
(2)在系统目录中找到:windows/system32/inesrv/metabase.xml”文件,找个文本编辑器打开,查找AspMaxRequestEntityAllowed="204800"这一项,这就是iis上传文件的默认大小了,默认为204800Byte,也就是200KB,将它改为需要的大小就可以了。
 
备注:
在页面结构里,我们需要给一个input用来上传文件: 
<input type="file" id="File"> 
则在支持FileReader的浏览器里就可以这样写: 
document.getElementById("File").addEventListener("change", readFile, false); 
这是在监听input的change事件,一旦选择了文件,触发了change事件,即刻调用readFile方法。
 

FormData

 

//上传图片触发事件    function company_Logo() {        var rows = $("#company_dg").datagrid("getChecked");        if (rows.length < 1) {            $.show_warning("提示", "请先勾选记录");            return;        }        $("#logoImage").click();    }

 

document.getElementById("logoImage").addEventListener("change", function () {            var rows = $("#company_dg").datagrid("getChecked");            var id = rows[0].Id;            var formdata = new FormData();            formdata.append('logoImage', $('#logoImage')[0].files[0]);            formdata.append('Id', id);            $.ajax({                type: "post",                url: "/Company/LogoImage",                data: formdata,                processData: false,                contentType: false,                async: true,                cache: false,                success: function (data) {                    var result = eval('(' + data + ')');                    if (result.Success == "true") {                        $.show_warning("提示", result.Message);                        company_databind();                    } else {                        $.show_warning("提示", result.Message);                    }                },                error: function () {                }            });        });

 

public string LogoImage()//设置头像        {            ResponseMessage responseMessage = new ResponseMessage();            Company originCompany = _companyRepository.GetSingle(Request["Id"]);            try            {                var file = Request.Files["logoImage"];                //保存                if (file != null && file.ContentLength > 0 && file.ContentLength <= 2 * 1024 * 1024)                {                    string[] strs = file.FileName.Split('.');                    string fileType = strs[strs.Length - 1];                    string fileName = string.Format("{0:yyyyMMddhhmmssfff}", DateTime.Now) + "." + fileType;                    string path = Server.MapPath("~") + "Upfiles\\Logo\\" + fileName;                    if (System.IO.File.Exists(path))                        System.IO.File.Delete(path);                    file.SaveAs(path);                    FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);                    Byte[] byteData = new Byte[fileStream.Length];                    fileStream.Read(byteData, 0, byteData.Length);                    fileStream.Close();                    originCompany.Logo = "/Upfiles/Logo/" + fileName;                    _companyRepository.Update(originCompany);                    responseMessage.Message = "/Upfiles/Logo/" + fileName;                    responseMessage.Success = "true";                    return JSON.Instance.ToJSON(responseMessage, JSONConfig.GetJSONParameters());                }                else                {                    if (file != null && file.ContentLength > 2 * 1024 * 1024)                    {                        responseMessage.Message = "Logo大小不能超过2M!";                        responseMessage.Success = "false";                        return JSON.Instance.ToJSON(responseMessage, JSONConfig.GetJSONParameters());                    }                    else                    {                        responseMessage.Message = "上传失败";                        responseMessage.Success = "false";                        return JSON.Instance.ToJSON(responseMessage, JSONConfig.GetJSONParameters());                    }                }            }            catch (Exception ex)            {                responseMessage.Message = "上传失败!";                responseMessage.Success = "false";                return JSON.Instance.ToJSON(responseMessage, JSONConfig.GetJSONParameters());            }        }

 

 

 

转载地址:http://vgoml.baihongyu.com/

你可能感兴趣的文章
使用cygwin/openSSH搭建windows下的SSH服务器
查看>>
Ubuntu里网卡IP设置的步骤&/etc/passwd文件
查看>>
Windows系统中 五大免费开源的SVN工具
查看>>
排序规则引起的冲突问题
查看>>
我的友情链接
查看>>
onTouch事件传递机制
查看>>
那些年的坑--双精度数值转成整形
查看>>
office 2007各种格式附件下载后变成zip文件问题解决方法
查看>>
宽依赖、窄依赖
查看>>
好程序员web前端系列之CSS3-3D
查看>>
xm 命令详解
查看>>
HttpClient4.x send json request
查看>>
mysql5.6基于GTID的主从复制
查看>>
iOS 获取Wifi的SSID及MAC地址
查看>>
认识六个被误解的Ruby特性
查看>>
Java线程:并发协作-生产者消费者模型
查看>>
libvirt API非阻塞调用及相关的原理分析
查看>>
老男孩第十四期Python学习班之Day06
查看>>
更改sql 数据库 SA密码 找不到sp_password存储过程
查看>>
破解软件注册码
查看>>