Upload files in ASP.NET MVC with JavaScript and C#
来源:互联网 发布:淘宝卖家怎么评差评 编辑:程序博客网 时间:2024/05/17 03:18
<span style="color: inherit; font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">GOOGLE的地址被封了,转过来,方便需要的人</span>
https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/
In an earlier post, I described how to implement a file upload using Ajax and ASP.NET WebAPI. This works great but it means that you need to have a WebAPI controller to manage the requests. If you already have a WebAPI in your solution then you can simply extend it to manage file uploads. However, there's no reason to add a WebAPI only for file uploads. Instead you can use an MVC controller to perform the same task.
The goal is to upload a file to the server using just JavaScript and an MVC controller without submitting a form. Most of the examples I found out there require a form submission. But there are a lot of situations where a form submission may not be desirable. The code example below takes advantage of jQuery andAjax on the client side to post a file to an ASP.NET MVC controller and save the file on disk.
NOTE - make sure you check that your browser supports
window.formdata
before implementing this solution. You can find information about the supported browsers here: http://caniuse.com/#search=formdata
HTML/JAVASCRIPT CODE
First we need to add an <input type=file...
element on the page to allow users to browse and upload files.
<div> <input type="file" name="UploadFile" id="txtUploadFile" class="makethispretty" /></div>
Now, lets add the javascript code to glue everything together:
$('#txtUploadFile').on('change',function (e) {var files = e.target.files;//var myID = 3; //uncomment this to make sure the ajax URL worksif (files.length> 0) {if (window.FormData!== undefined) {var data = new FormData();for (var x= 0; x < files.length; x++){data.append("file"+ x, files[x]);}$.ajax({type: "POST",url: '/MyController/UploadFile?id='+ myID,contentType: false,processData: false,data: data,success:function(result) {console.log(result);},error:function (xhr,status, p3, p4){var err = "Error" + "" + status +"" + p3 + " " + p4;if (xhr.responseText&& xhr.responseText[0]== "{")err = JSON.parse(xhr.responseText).Message;console.log(err);}});} else {alert("This browser doesn't support HTML5 file uploads!");}}});
This method works by attaching an event listener to the textbox input element using jQuery
and 'fire' on change, i.e when the user browses and selects a file(s). We then create a new FormData object where we load all the file data.
The last step is to perform the ajax call which posts the data to the MVC contoller and logs the success to the console.
MVC CONTROLLER
The MVC controller method is outlined below:
The method accepts an id parameter (of type string) and reads the file data from the Request. To persist the file to disk, we get the filename
and then use a FileStream
to write the data to the destination path
.
Bonus: the method can process multiple files within a single request, so you can change your input element to enable multiple file upload like this:
<input type="file" name="File Upload" id="txtUploadFile" multiple>
It is important to note that there are many different ways to upload files to the server in MVC ASP.NET, so you should choose the one that better matches your requirements. You can find implementation to two ways below:
- file upload with WebAPI
- file upload with MVC
The choice is yours...
- Upload files in ASP.NET MVC with JavaScript and C#
- Multiple Files Upload in ASP.NET and ASP.NET with jQuery
- Upload Files Using ASP.NET Impersonation and UNC Share
- ASP.NET MVC Uploading and Downloading Files
- File Upload with ASP.NET
- Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application
- Working-with-files-in-javascript
- Working with Files in C#
- Essential ASP.NET With Examples in C#
- Essential ASP.NET with Examples in C#
- MVC architecture in ASP.Net using C#
- ASP.NET File Upload with Progress Bar
- MVC architecture in ASP.Net using C# and Microsoft Data Access Application block
- Working with Roles in ASP.NET MVC 4+
- ASP.NET MVC 3: Layouts and Sections with Razor
- Getting Started with NHibernate and ASP.NET MVC- CRUD Operations
- Twitter style paging with ASP.NET MVC and jQuery
- Unobtrusive JavaScript in ASP.NET MVC 3javascript
- HDU 2546 饭卡(01背包)
- Maven plugin中的lifecycle、phase、goal概念及作用的理解
- win10运行慢的解决
- View编程引导(官文)——1 概述
- Linux内核Makefile.txt文件翻译
- Upload files in ASP.NET MVC with JavaScript and C#
- 138. Copy List with Random Pointer
- 马士兵Java课堂笔记-7-键盘事件测试代码
- EditView、ImageView、Button
- AFN上传多张图片到服务器
- Image图片的压缩使用
- 那些被漏掉的JQuery总结(三)——关于前台的数据计算问题
- Eclipse构建Maven项目
- 公众平台调整SSL安全策略,请开发者注意升级