如果你使用 C# 作为后端,你可以试试这个(客户端,JQuery):
$("#btnUpload").click(function () { // btnUpload is the ID of any button for upload
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/UploadMethod'); // UploadMethod is your back-end code
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// alert("uploaded");
}
}
});
然后在你 UploadMethod 做这样的事情:(ServerSide,C#)
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
var appPath = HostingEnvironment.ApplicationPhysicalPath + "Documents/" + "_" + DateTime.Now+ fileName;
file.SaveAs(appPath); //File will be saved in Documents folder
}
}