博客
关于我
强烈建议你试试无所不能的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/

你可能感兴趣的文章
10.25作业
查看>>
Content is not allowed in prolog错误
查看>>
383. 装最多水的容器
查看>>
MVC3.0----整理之一
查看>>
linux中磁盘分区以及如何将磁盘挂载到系统中
查看>>
装饰器
查看>>
iOS开发-UI基础Demo
查看>>
wcf微软列子
查看>>
Oracle 相关概念
查看>>
Oracle中函数/过程返回结果集的几种方式
查看>>
PowerDesigner连接Oracle并导出表结构
查看>>
重建二叉树
查看>>
Winform 显示远程图片
查看>>
MS14-025引起的问题 - 2
查看>>
.Net开源网络爬虫Abot介绍
查看>>
Sqoop -- 用于Hadoop与关系数据库间数据导入导出工作的工具
查看>>
bzoj1072排列
查看>>
超简单全选/反选/不选
查看>>
js异步和单线程
查看>>
滚动数组
查看>>