我一直在尝试让这个工作起来,但是一直没有成功。
我的目标是使用JQuery AJAX上传一组FormData图像和附件。
我不断收到错误消息:“Multipart body length limit 16384 exceeded”
我在SO上找到了一个类似的问题: Multipart body length limit exceeded exception
如果有人能帮我或指点我方向,我将不胜感激。现在对我来说已经快到午夜了,我要放弃了 :(。
我正在使用ASP.NET Core 1.1。
以下是我的JavaScript代码:
let data = new FormData();
data.enctype = "multipart/form-data";
let file = $("#imgItem_image-upload-file")[0].files[0];
data.append("image|" + file.name, file); //Works fine if alone.
//Does not work, causes error on server side.
for (var i = 0; i < objItem.Attachments[0].length; i++) {
let attFile = objItem.Attachments[0][i].File;
console.log(attFile);
data.append("attachment|" + attFile.name, attFile);
}
data.append("Category", objItem.Category);
data.append("NewCategory", objItem.NewCategory);
data.append("Name", objItem.Name);
data.append("IdentificationType", objItem.IdentificationType);
data.append("SerialNumber", objItem.SerialNumber);
data.append("IMEI", objItem.IMEI);
data.append("EngineNumber", objItem.EngineNumber);
data.append("MASNumber", objItem.MASNumber);
data.append("NumberPlate", objItem.NumberPlate);
data.append("VINNumber", objItem.VINNumber);
data.append("Description", objItem.Description);
$.ajax({
url: "http://localhost:7001/api/AddPersonalItem",
type: "POST",
data: data,
//dataType: "json",
//headers: { 'Content-Type': false },
//contentType: false,
contentType: false, //'multipart/form-data'
processData: false,
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// },
success: function (response) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
我也将这个内容添加到我的Startup.js文件中:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
//Multipart
services.Configure<FormOptions>(x =>
{
x.MultipartBodyLengthLimit = 60000000;
});
}
这是我的API控制器代码:
public ServiceCallResponse AddPersonalItem()
{
ItemObject io = new ItemObject();
io.Attachments = new List<Attachment>();
io.Image = new Image();
//Get files.
foreach (IFormFile file in Request.Form.Files)
{
//The file name also states what type of object this is.
string type = file.Name.Split('|')[0];
string name = file.Name.Split('|')[1];
StreamReader reader = new StreamReader(file.OpenReadStream());
byte[] bytes = Encoding.Unicode.GetBytes(reader.ReadToEnd());
string base64 = Convert.ToBase64String(bytes);
switch (type.ToLower().Trim())
{
case "attachment":
Attachment a = new Attachment();
a.Name = name;
a.Base64 = base64;
io.Attachments.Add(a);
break;
case "image":
io.Image.Name = name;
io.Image.Base64 = base64;
break;
}
}
}
尽管增加了多部分正文长度,我仍然遇到完全相同的错误。
错误发生在:
foreach (IFormFile file in Request.Form.Files)
如果我表述不够清楚,请告诉我,我会尝试详细解释!:)
.NET Standard
中是否有与FormOptions
等效的选项,因为我的解决方案是基于.NET Standard
的,而且我遇到了关于HTML
表单的相同错误。 - Bercovici Adrian