Upload files in ASP.NET MVC with JavaScript and C#

<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 works

if (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:

  [HttpPost]
  public async Task<JsonResult> UploadHomeReport(string id)
  {
  try
  {
  foreach (string filein Request.Files)
  {
  var fileContent = Request.Files[file];
  if (fileContent !=null && fileContent.ContentLength >0)
  {
  // get a stream
  var stream = fileContent.InputStream;
  // and optionally write the file to disk
  var fileName = Path.GetFileName(file);
  var path = Path.Combine(Server.MapPath("~/App_Data/Images"), fileName);
  using (var fileStream = File.Create(path))
  {
  stream.CopyTo(fileStream);
  }
  }
  }
  }
  catch (Exception)
  {
  Response.StatusCode = (int)HttpStatusCode.BadRequest;
  return Json("Upload failed");
  }
   
  return Json("File uploaded successfully");
  }
view raw fileupload.cs hosted with ❤ by  GitHub

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:

扫描二维码关注公众号,回复: 10047139 查看本文章
<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:

The choice is yours...

Ani
发布了83 篇原创文章 · 获赞 11 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/Ani/article/details/51447340