Asp.net mvc 3 file uploads using the fileapi
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的更多相关文章
- asp.net mvc return file result
asp.net mvc返回文件: public ActionResult ExportReflection(string accessToken) { var reflections = GetCms ...
- ASP.Net MVC upload file with record & validation - Step 6
Uploading file with other model data, validate model & file before uploading by using DataAnnota ...
- [转]File uploads in ASP.NET Core
本文转自:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads By Steve Smith ASP.NET MVC ...
- ASP.NET MVC file download sample
ylbtech- ASP.NET MVC:ASP.NET MVC file download sample 功能描述:ASP.NET MVC file download sample 2,Techno ...
- ASP.NET MVC下使用文件上传
这里我通过使用uploadify组件来实现异步无刷新多文件上传功能. 1.首先下载组件包uploadify,我这里使用的版本是3.1 2.下载后解压,将组件包拷贝到MVC项目中 3. 根目录下添加新 ...
- 在asp.net mvc中上传大文件
在asp.net mvc 页面里上传大文件到服务器端,需要如下步骤: 1. 在Control类里添加get 和 post 方法 // get method public ActionResult Up ...
- Asp.net MVC 处理文件的上传下载
如果你仅仅只有Asp.net Web Forms背景转而学习Asp.net MVC的,我想你的第一个经历或许是那些曾经让你的编程变得愉悦无比的服务端控件都驾鹤西去了.FileUpload就是其中一个, ...
- ASP.NET MVC 4 批量上传文件
上传文件的经典写法: <form id="uploadform" action="/Home/UploadFile" method="post& ...
- 利用Asp.net MVC处理文件的上传下载
如果你仅仅只有Asp.net Web Forms背景转而学习Asp.net MVC的,我想你的第一个经历或许是那些曾经让你的编程变得愉悦无比的服务端控件都驾鹤西去了.FileUpload就是其中一个, ...
随机推荐
- Nginx的安装及反向代理设置
因为项目的缘故,接触到了Nginx的安装和反向代理设置,和大家分享下. 一.Nginx的下载.安装cd /homewget http://nginx.org/download/nginx-1.0.5. ...
- JS原型的剖析与理解
原型相关的概念 关于面向对象的概念 类 class 在js中就是构造函数 在传统的面向对象语言中,使用一个叫类的东西定义模版,然后使用模版创建对象 在构造方法中也具有类似的功能,因此称其为类 实例与对 ...
- shopnc B2B2C商城 Nginx下开启伪静态
B2B2C商城 Nginx下开启伪静态,伪静态开启后,对系统的SEO极为有利,可以最大限度让商城页面被搜索引擎抓取,但在实际安装中,很多客户在这块都会遇到各种各样的问题. 1. 编辑商城配置文件(da ...
- DOMElement之Offset
有明确目的的学习比较有效,我学习HTML offset相关概念是出自一个需求,那就是计算一个绝对定位的HTML元素相对于当前窗口的偏移距离,主要是Y方向的偏移,X方向同理. 要实现这个目的,首先要弄清 ...
- Lintcode--010(最长上升子序列)
给定一个整数序列,找到最长上升子序列(LIS),返回LIS的长度.LIS(longestIncreasingSubsequence) 说明: 最长上升子序列的定义: 最长上升子序列问题是在一个无序的给 ...
- Java日志最佳实践
http://www.ibm.com/developerworks/cn/java/j-lo-practicelog/
- 递归转手工栈处理的一般式[C语言]
是任意形式的递归,是化解的一般式. 主题所谓的“递归调用化解为栈处理”,意思是,将递归函数调用化解为“一个由stack_push stack_pop stack_top等函数调用组成的循环式子”.这里 ...
- 转:linux shell 数组建立及使用技巧
linux shell在编程方面比windows 批处理强大太多,无论是在循环.运算.已经数据类型方面都是不能比较的. 下面是个人在使用时候,对它在数组方面一些操作进行的总结. 1.数组定义 [che ...
- 【转】Win7、Ubuntu双系统正确卸载Ubuntu系统--不错
原文网址:http://my.oschina.net/u/1377657/blog/281872 如果ubuntu不是以wubi方式安装的,而是U盘或者光盘装的双系统,那么卸载ubuntu时要慎重,不 ...
- Delphi 调试 通过BreakPoint
1.打个断点, 如下图 2. 在断点上,邮件,如下图 3. 弹出一个窗体 ,如下图 在 condition 中写条件就可以了. 这样就可以按你假设的条件来进行了,方便.