asp.net文件上传

1.AjaxFileUpload

地址:http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

下载:ajaxfileupload.rar

   js:

<script type="text/javascript">
    function ajaxFileUpload() {
        $.ajaxFileUpload(
            {
                url: '/Home/AjaxSave',
                secureuri: false,
                fileElementId: 'fileToUpload',
                dataType: 'json',
                beforeSend: function () {

                },
                complete: function () {

                },
                success: function (data, status) {
                    if (typeof (data.error) != 'undefined') {
                        if (data.error != '') {
                            alert(data.error);
                        } else {
                            alert(data.msg);
                        }
                    }
                },
                error: function (data, status, e) {
                    alert(e);
                }
            }
        );
        return false;
    }
</script>

    Html:

<input id="fileToUpload" type="file" size="45" name="fileToUpload" />
<input type="button" id="buttonUpload" onclick="return ajaxFileUpload();" value="Upload" />

   后台:

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文件上传

FileUplaodDemo.rar

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

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //文件列表
        $.post("/Borrow/FileList", null, function (data) {
            $("#fileList").html(data);
        });
        //提交图片之后的ajax请求更新
        $("#fileList").click(function () {
            $.post("/Home/FileList", null, function (data) {
                $("#fileList").html(data);
                $("#fileToUpload").val(null);
            });
        });
    });
</script>
<div>
    <div id="fileList">
        文件列表
    </div>
    <br />
    @using (Html.BeginForm("Upload", "Home", FormMethod.Post, htmlAttributes: new { enctype = "multipart/form-data", target = "msgframe" }))
    {
        <input id="fileToUpload" type="file" size="45" name="fileToUpload" />
        <input type="submit" style="cursor: pointer;" value="上传" />
    }
    <iframe id="msgframe" name="msgframe" style="display: none;"></iframe>
</div>

    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("<script>alert('" + msg + "');</script>"); } Response.Write("<script>parent.document.getElementById('fileList').click();</script>"); 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;
}

<!DOCTYPE html>
<html>
<head>
    <title>Upload</title>
</head>
<body>
    <div>
        
    </div>
</body>
</html>

 补充:

<form name="formToUpload" method="post" action="..\loadjsonM\productPlan_JhJson.ashx" enctype="multipart/form-data" target="msgframe">
    <input id="fileToUpload" type="file" size="45" name="fileToUpload" />
    <input type="submit" style="cursor: pointer;" value="上传" />
    <input name="uptype" type="hidden" value="55" />
</form>
<iframe id="msgframe" name="msgframe" style="display: none;"></iframe>

 

                    string strReturn =
@"
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type='text/javascript'>
        @msg
    </script>
</head>
<body>
</body>
</html>
";
                    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("");
        }
    }
<div style="display:none;">
    <form id="formUpload" name="formToUpload" method="post" action="Accessory/Upload" enctype="multipart/form-data" target="msgframe">
        <input id="fileToUpload" type="file" size="45" name="fileToUpload" />
    </form>
    <iframe id="msgframe" name="msgframe" style="display: none;"></iframe>
</div>

 

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

<div style="display: none;">
        <input type="file" id="logoImage" name="logoImage" accept="image/*" style="width: 175px;" />
    </div>

 

    //上传图片触发事件
    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());
            }
        }

 

 

 

posted on 2012-12-12 19:32  凡一二三  阅读(1685)  评论(0编辑  收藏  举报