2
我已經檢出了一些articals,並且我無法成功使用XMLHttpRequest和FormData對象將文件發送到服務器。如何使用XMLHttpRequest和formdata將文件發送到服務器
當調試我的C#.NET代碼在upload.aspx的頁面加載文件的請求對象的文件屬性始終具有0
計數我缺少哪一部分,這樣我可以發送文件異步到服務器?
--html
<input type="file" id="upload" accept="image/*" onchange="handleFile(this.files)" name="file" />
--js
function handleFile(files) {
var fileReader = new FileReader();
var file = files[0];
var imageElem = document.createElement("img");
debugger
fileReader.onload = (function (img) { return function (e) { img.src = e.target.result; }; })(imageElem);
fileReader.readAsDataURL(file);
document.getElementById("images").appendChild(imageElem);
uploadFile(file);
}
function uploadFile(file) {
debugger
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/upload.aspx", true);
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);
xhr.send(formData);
}
--C#
protected void Page_Load(object sender, EventArgs e)
{
HttpPostedFile file = null;
if (Request.Files.Count > 0)
{
file = Request.Files[0];
//file.SaveAs(Server.MapPath("~/myfile.txt"));
}
}
--SnapShot
--------------------找到了答案這裏------- ----------------------------
File API File Upload - Read XMLHttpRequest in ASP.NET MVC