Asp.net mvc 3 file uploads using the fileapi

I was recently given the task of adding upload progress bars to some internal applications. A quick search of the internet yielded SwfUpload. Which worked…but not in the way that I wanted. So I went the route of using the new FileApi. It didn’t function the way that I’ve been used to standard file uploads. This is how I made it work in MVC3.

Setup

First let’s just setup a basic upload form so that we have one that works in almost every browser.

@using(Html.BeginForm("uploadfile","home",FormMethod.Post,new{ enctype ="multipart/form-data"})){<input id="files-to-upload" type="file" name="file"/><input type='submit' id='upload-files' value=' Upload Files '/>}[HttpPost]publicActionResultUploadFile(HttpPostedFileBase file){if(file !=null){Uploads.Add(file);}returnRedirectToAction("index);
}

Uploads is just a static collection so that we can easily return the file if requested.

Using the FileApi

Since this project is supposed to have a progress bar and allow multiple file uploads we’re going to make a few changes to the form.

@using(Html.BeginForm("uploadfile","home",FormMethod.Post,new{ enctype ="multipart/form-data"})){<input id="files-to-upload" type="file" multiple name="file"/><input type='submit' id='upload-files' value=' Upload Files '/><div class='progress-bar'></div>}

Notice the multiple keyword added to the input. I’ve also added a progress-bar div for later. We need to override the submit button to use the FileApi rather than the standard POST.

<scripttype="text/javascript">
$(function(){//is the file api available in this browser//only override *if* available.if(newXMLHttpRequest().upload){
$("#upload-files").click(function(){//upload files using the api//The files property is available from the//input DOM object
upload_files($("#files-to-upload")[0].files);returnfalse;});}});//accepts the input.files parameterfunction upload_files(filelist){if(typeof filelist !=="undefined"){for(var i =0, l = filelist.length; i < l; i++){
upload_file(filelist[i]);}}}//each file upload produces a unique POSTfunction upload_file(file){
xhr =newXMLHttpRequest(); xhr.upload.addEventListener("progress",function(evt){if(evt.lengthComputable){//update the progress bar
$(".progress-bar").css({
width:(evt.loaded / evt.total)*100+"%"});}},false);// File uploaded
xhr.addEventListener("load",function(){
$(".progress-bar").html("Uploaded");
$(".progress-bar").css({ backgroundColor:"#fff"});},false); xhr.open("post","home/uploadfile",true);// Set appropriate headers// We're going to use these in the UploadFile method// To determine what is being uploaded.
xhr.setRequestHeader("Content-Type","multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);// Send the file
xhr.send(file);}</script>

Now that we have this new upload script we’re going to have to update the back end to accommodate. I’ve created a new model called UploadedFile that will hold our upload regardless of where it came from.

publicclassUploadedFile{publicintFileSize{get;set;}publicstringFilename{get;set;}publicstringContentType{get;set;}publicbyte[]Contents{get;set;}}

In our home controller I’ve added the following method. It checks to see where the upload came from. If it came from the normal POST the Request.Files will be populated otherwise it will be part of the post data.

privateUploadedFileRetrieveFileFromRequest(){string filename =null;string fileType =null;byte[] fileContents =null;if(Request.Files.Count>0){//they're uploading the old wayvar file =Request.Files[0];
fileContents =newbyte[file.ContentLength];
fileType = file.ContentType;
filename = file.FileName;}elseif(Request.ContentLength>0){
fileContents =newbyte[Request.ContentLength];Request.InputStream.Read(fileContents,0,Request.ContentLength);
filename =Request.Headers["X-File-Name"];
fileType =Request.Headers["X-File-Type"];}returnnewUploadedFile(){Filename= filename,ContentType= fileType,FileSize= fileContents !=null? fileContents.Length:0,Contents= fileContents
};}

The UploadFile method will change slightly to use RetrieveFileFromRequest instead of taking directly from the Request.Files.

[HttpPost]publicActionResultUploadFile(){UploadedFile file =RetriveFileFromRequest();if(file.Filename!=null&&!Uploads.Any(f => f.Filename.Equals(file.Filename)))Uploads.Add(file);returnRedirectToAction("index);
}

It’s that simple. The only real difference between the two methods is that the HttpRequest.Files is not populated when using the FileApi. This can easily be used to create a Drag/Drop scenario by passinge.dataTransfer.files from the drop event into upload_files.

-Ben Dornis

http://buildstarted.com/2011/07/17/asp-net-mvc-3-file-uploads-using-the-fileapi/

Asp.net mvc 3 file uploads using the fileapi的更多相关文章

  1. asp.net mvc return file result

    asp.net mvc返回文件: public ActionResult ExportReflection(string accessToken) { var reflections = GetCms ...

  2. ASP.Net MVC upload file with record & validation - Step 6

    Uploading file with other model data, validate model & file before uploading by using DataAnnota ...

  3. [转]File uploads in ASP.NET Core

    本文转自:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads By Steve Smith ASP.NET MVC ...

  4. ASP.NET MVC file download sample

    ylbtech- ASP.NET MVC:ASP.NET MVC file download sample 功能描述:ASP.NET MVC file download sample 2,Techno ...

  5. ASP.NET MVC下使用文件上传

    这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解压,将组件包拷贝到MVC项目中 3.  根目录下添加新 ...

  6. 在asp.net mvc中上传大文件

    在asp.net mvc 页面里上传大文件到服务器端,需要如下步骤: 1. 在Control类里添加get 和 post 方法 // get method public ActionResult Up ...

  7. Asp.net MVC 处理文件的上传下载

    如果你仅仅只有Asp.net Web Forms背景转而学习Asp.net MVC的,我想你的第一个经历或许是那些曾经让你的编程变得愉悦无比的服务端控件都驾鹤西去了.FileUpload就是其中一个, ...

  8. ASP.NET MVC 4 批量上传文件

    上传文件的经典写法: <form id="uploadform" action="/Home/UploadFile" method="post& ...

  9. 利用Asp.net MVC处理文件的上传下载

    如果你仅仅只有Asp.net Web Forms背景转而学习Asp.net MVC的,我想你的第一个经历或许是那些曾经让你的编程变得愉悦无比的服务端控件都驾鹤西去了.FileUpload就是其中一个, ...

随机推荐

  1. linux下环境搭建比较

    xampp是一款初学者使用的集成的apache mysql与php配置安装包了,我们可以利用xampp来快速安装配置php环境,下面一起来看看吧.   要在linux服务器上面挂我们的php网站程序, ...

  2. eclipse安装lombok插件

    1:下载jar https://projectlombok.org/download.html 2:双击下载的lombok.jar 安装 3:如果eclipse没有安装到默认目录,需要手动选择ecli ...

  3. 基于htmlparser实现网页内容解析

    基于htmlparser实现网页内容解析 网页解析,即程序自动分析网页内容.获取信息,从而进一步处理信息. 网页解析是实现网络爬虫中不可缺少而且十分重要的一环,由于本人经验也很有限,我仅就我们团队开发 ...

  4. Swift—静态属性- 备

    我先来设计一个类:有一个Account(银行账户)类,假设它有3个属性:amount(账户金额).interestRate(利率)和owner(账户名). 在这3个属性中,amount和owner会因 ...

  5. Eclipse快捷键集结

    Debug快捷键 F5单步调试进入函数内部.   F6单步调试不进入函数内部,如果装了金山词霸2006则要把“取词开关”的快捷键改成其他的.   F7由函数内部返回到调用处.   F8一直执行到下一个 ...

  6. 【转】Windows SDK入门浅谈

    前言 如果你是一个编程初学者,如果你刚刚结束C语言的课程.你可能会有点失望和怀疑:这就是C语言吗?靠它就能编出软件?无法想象Windows桌面上一个普通的窗口是怎样出现在眼前的.从C语言的上机作业到W ...

  7. PCB Layout 中的高频电路布线技巧

    1.多层板布线 高频电路往往集成度较高,布线密度大,采用多层板既是布线所必须,也是降低干扰的有效手段.在PCB Layout阶段,合理的选择一定层数的印制板尺寸,能充分利用中间层来设置屏蔽,更好地实现 ...

  8. translate函数说明

    TRANSLATE(expr, from_string, to_string) from_string 与 to_string 以字符为单位,对应字符一一替换. SQL> SELECT TRAN ...

  9. BaseAdapter自定义适配器——思路详解

    BaseAdapter自定义适配器——思路详解 引言: Adapter用来把数据绑定到扩展了AdapterView类的视图组.系统自带了几个原生的Adapter. 由于原生的Adapter视图功能太少 ...

  10. zoj2562:搜索+数论(反素数)

    题目大意:求n以内因子数量最多的数  n的范围为1e16 其实相当于求n以内最大的反素数... 由素数中的 算数基本原理 设d(a)为a的正因子的个数,则 d(n)=(a1+1)(a2+1)..... ...