我有实体框架6.0的web项目 我在xmlhttprequest中使用Javascript上传文件 但是在服务器端,当我想用request.files捕获文件时 request.files是空的! 我使用dropzone上传文件,但是在没有结果的一段时间之后我尝试下面的js代码 但问题与dropzone.js相同
我尝试过:
javascript代码:
var that = this;
debugger;
var url = "../../Ajax/GlobalHandler.aspx?Command=UploadImage";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// Every thing ok, file uploaded
console.log(xhr.responseText); // handle response.
}
};
fd.append("upload_file", file);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
//xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(fd);
c#code:
Guid fileGuid = Guid.NewGuid();
string fileName = string.Empty;
foreach (string s in Request.Files)
{
HttpPostedFile File = Request.Files[s];
if (File == null || string.IsNullOrEmpty(File.FileName))
continue;
var fileContent = new byte[File.InputStream.Length];
File.InputStream.Read(fileContent, 0, fileContent.Length);
File.InputStream.Close();
File.InputStream.Dispose();
var dot = File.FileName.LastIndexOf(".");
var ext = string.Empty;
if (dot >= 0)
ext = File.FileName.Substring(dot + 1);
fileName = fileGuid.ToString() + (string.IsNullOrEmpty(ext) ? string.Empty : "." + ext);
FileStream filestream = new FileStream(Context.Server.MapPath("~/App_Data") + "\\" + fileName, FileMode.Create);
filestream.Write(fileContent, 0, fileContent.Length);
filestream.Close();
filestream.Dispose();
}