我正在尝试使用Ajax
上传文件。
Error status
为200
ok
。
回复文字是我的MasterPage
HTML
代码。
请求从未进入后端,因为我正在使用断点调试方法。
到目前为止,我已经尝试过了。C#WebMethod
[HttpPost]
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
file.SaveAs(path);
}
}`
Ajax请求
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
答案 0 :(得分:1)
您必须删除dataType: json
,因为必须发送文件multipart/form-data
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
答案 1 :(得分:0)
请尝试此代码
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return reader.result;
};
reader.onerror = function (error) {
return '';
};
}
function uploadFiles() {
var files=[];
$.each(files, function (key, value) {
var x=getBase64(value)
if(!!x)
files.push(x);
});
$.ajax({
type: 'POST',
url: '/Home.aspx/Upload',
data: JSON.stringity({files:files}),
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
[System.Web.Services.WebMethod]
public static void Upload(string[] files)
{
//Convert base64 to file format and save
}