Upload files in AS.NET MVC with JavaScript and C刋
4793 ワード
GOOGLE , ,
https://cmatskas.com/upload-files-in-asp-net-mvc-with-javascript-and-c/In an earlier post、I described how to implement a file uload using Ajax and ASP.NET WebAPI.This works great but t t it means thaaat t t t t t need to have a WebAPI contrtroller to manaage the requests.If you already have a WebAPI inyoursosososoursosososon sososososososoninininion then mimimimimimimplyeeeeeeeeeeeeeeeeeeeeeeeeeexteteteteteteteteteteteted to to to to to to to to to mamananananaagitititititititititititititititititititititititititititititititsame task.
The goal is to uplad a file to the server using just JavaScript and an MVC controller without submitting a form.Most of the examples I found there require a form submission.But there re are a lot of situations where a form submission may not be desirable.The code example beloe below Tandes vantage of jQuery and Ajax on the client side to post a file to an AS P.NET MVC controller and save the file on disk.
NOTE-make sure you check that your browser supports
window.formdata
before implement ing this solution.You can find information about the supported browsers here: http://caniuse.com/#search=formdata HTML/JAVSCRIPTコード
First we need to add an
element on the page to allow users to browse and upload files.
Now、lets add the javascript code to glue everthing 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 ataching an event listener to the textbox input element using jQuery
and'fire'on change,i.e when the user browses and selects a file.We the n 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 consolie.
MVC CONTROLLER
The MVC controller method is outlind below:
[HttpPost]
public async Task UploadHomeReport(string id)
{
try
{
foreach(string filein Request.Files)
{
var fileContent=Request.Files[file]
if(fileContent!=null&fileContent.connt Length>0)
{
//get a stream
var stream=fileContent.InputStream;
//and optionly write the file to disk
var fileName=Path.GetFileName(file)
var path=Path.Commbine(Server.MapPath);
using(var fileStream=File.reate(path)
{
stream.CoopyTo(fileSteream);
)
)
)
)
catch(Exception)
{
Resonse.Sttus Code=(int)HttpStatus Code.BadRequest;
return Json(「Upload failed」);
)
return Json(「File uploaded success fully」);
)
view raw fileuplad.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 multile file upled like this:
It is importt to note that there are many different ways to uplad files to the server in MVC AS.NET,so you shoud chose the one that better matche your requirements.You find implement to ways