Asp.net web api Web API 2中的文件上载问题,html表单post除外
Web API 2中的文件上载问题 虽然我用form post上传文件,但当我从Rest客户端(如Google Chrome中的Postman)发送相同的信息,或者用Android或iOS应用程序发布文件信息时,Web Api 2代码并没有检测到文件多部分/form post 以下是我的html代码Asp.net web api Web API 2中的文件上载问题,html表单post除外,asp.net-web-api,asp.net-mvc-5,Asp.net Web Api,Asp.net Mvc 5,Web API 2中的文件上载问题 虽然我用form post上传文件,但当我从Rest客户端(如Google Chrome中的Postman)发送相同的信息,或者用Android或iOS应用程序发布文件信息时,Web Api 2代码并没有检测到文件多部分/form post 以下是我的html代码 <form enctype="multipart/form-data" method="post" action="/api/feedback"> <input t
<form enctype="multipart/form-data" method="post" action="/api/feedback">
<input type="text" name="Scope" placeholder="Scope" value="feedback">
<input type="text" name="Lang" placeholder="Lang" value="en">
<input type="text" name="Collection" placeholder="Collection" value="7b22437573746f6d65724964223a392c2253657276696365526571756573744964223a312c224174746974756465223a332e322c22576f726b457468696373223a342e322c2248796769656e65223a352c22416d6f757450616964223a333132332e327d">
<input type="file" name="Photo1" placeholder="Photo1">
<input type="file" name="Photo2" placeholder="Photo2">
<input type="file" name="Signature" placeholder="Signature">
<input type="submit" value="Submit">
</form>
public async Task<Result> Post()
{
var model = new ApiData();
var result = new Result();
if (Request.Content.IsMimeMultipartContent())
{
try
{
string root = HttpContext.Current.Server.MapPath("~/assets/temp");
var provider = new MultipartFormDataStreamProvider(root);
var sb = new System.Text.StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.Equals("Scope"))
model.Scope = val;
if (key.Equals("Lang"))
model.Lang = val;
if (key.Equals("Collection"))
model.Collection = val;
}
}
if (!model.Scope.Equals("feedback", StringComparison.InvariantCultureIgnoreCase))
result.Text = "Missing Scope.";
else
{
var Util = new Utils();
model.Collection = Util.ToString(model.Collection);
var _Feedback = JsonConvert.DeserializeObject<Feedback>(model.Collection);
try
{
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
string BaseUrl = HttpContext.Current.Server.MapPath("~/assets/feedback/");
string oldFile = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
string NewName = string.Format("{0}{1}", Util.NewGuid, Path.GetExtension(oldFile));
if (file.Headers.ContentDisposition.Name.ToLower().Contains("photo"))
{
_Feedback.Photos = string.IsNullOrEmpty(_Feedback.Photos) ? NewName : _Feedback.Photos + "," + NewName;
fileInfo.MoveTo(BaseUrl + NewName);
}
else if (string.IsNullOrEmpty(_Feedback.Signatures) && file.Headers.ContentDisposition.Name.ToLower().Contains("signature"))
{
_Feedback.Signatures = NewName;
fileInfo.MoveTo(BaseUrl + NewName);
}
}
}
catch { }
if (Util.IsRequired(_Feedback.CustomerId)
&& Util.IsRequired(_Feedback.ServiceRequestId)
&& Util.IsRequired(_Feedback.Attitude)
&& Util.IsRequired(_Feedback.WorkEthics)
&& Util.IsRequired(_Feedback.Hygiene)
)
{
var feedback = new Feedback()
{
CustomerId = _Feedback.CustomerId,
ServiceRequestId = _Feedback.ServiceRequestId,
Attitude = _Feedback.Attitude,
WorkEthics = _Feedback.WorkEthics,
Hygiene = _Feedback.Hygiene,
AmoutPaid = _Feedback.AmoutPaid,
Photos = _Feedback.Photos,
Signatures = _Feedback.Signatures,
Created = DateTime.UtcNow,
Updated = DateTime.UtcNow
};
db.Feedbacks.Add(feedback);
db.SaveChanges();
if (feedback.Id != default(int))
{
result.Success = true;
result.Text = "Success";
}
}
else
{
result.Text = "Required Parameters missing.";
}
}
}
catch
{
result.Text = "Error";
}
}
else
result.Text = "Signature or photo missing";
return result;
}
此.Net Web Api 2代码
<form enctype="multipart/form-data" method="post" action="/api/feedback">
<input type="text" name="Scope" placeholder="Scope" value="feedback">
<input type="text" name="Lang" placeholder="Lang" value="en">
<input type="text" name="Collection" placeholder="Collection" value="7b22437573746f6d65724964223a392c2253657276696365526571756573744964223a312c224174746974756465223a332e322c22576f726b457468696373223a342e322c2248796769656e65223a352c22416d6f757450616964223a333132332e327d">
<input type="file" name="Photo1" placeholder="Photo1">
<input type="file" name="Photo2" placeholder="Photo2">
<input type="file" name="Signature" placeholder="Signature">
<input type="submit" value="Submit">
</form>
public async Task<Result> Post()
{
var model = new ApiData();
var result = new Result();
if (Request.Content.IsMimeMultipartContent())
{
try
{
string root = HttpContext.Current.Server.MapPath("~/assets/temp");
var provider = new MultipartFormDataStreamProvider(root);
var sb = new System.Text.StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.Equals("Scope"))
model.Scope = val;
if (key.Equals("Lang"))
model.Lang = val;
if (key.Equals("Collection"))
model.Collection = val;
}
}
if (!model.Scope.Equals("feedback", StringComparison.InvariantCultureIgnoreCase))
result.Text = "Missing Scope.";
else
{
var Util = new Utils();
model.Collection = Util.ToString(model.Collection);
var _Feedback = JsonConvert.DeserializeObject<Feedback>(model.Collection);
try
{
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
string BaseUrl = HttpContext.Current.Server.MapPath("~/assets/feedback/");
string oldFile = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
string NewName = string.Format("{0}{1}", Util.NewGuid, Path.GetExtension(oldFile));
if (file.Headers.ContentDisposition.Name.ToLower().Contains("photo"))
{
_Feedback.Photos = string.IsNullOrEmpty(_Feedback.Photos) ? NewName : _Feedback.Photos + "," + NewName;
fileInfo.MoveTo(BaseUrl + NewName);
}
else if (string.IsNullOrEmpty(_Feedback.Signatures) && file.Headers.ContentDisposition.Name.ToLower().Contains("signature"))
{
_Feedback.Signatures = NewName;
fileInfo.MoveTo(BaseUrl + NewName);
}
}
}
catch { }
if (Util.IsRequired(_Feedback.CustomerId)
&& Util.IsRequired(_Feedback.ServiceRequestId)
&& Util.IsRequired(_Feedback.Attitude)
&& Util.IsRequired(_Feedback.WorkEthics)
&& Util.IsRequired(_Feedback.Hygiene)
)
{
var feedback = new Feedback()
{
CustomerId = _Feedback.CustomerId,
ServiceRequestId = _Feedback.ServiceRequestId,
Attitude = _Feedback.Attitude,
WorkEthics = _Feedback.WorkEthics,
Hygiene = _Feedback.Hygiene,
AmoutPaid = _Feedback.AmoutPaid,
Photos = _Feedback.Photos,
Signatures = _Feedback.Signatures,
Created = DateTime.UtcNow,
Updated = DateTime.UtcNow
};
db.Feedbacks.Add(feedback);
db.SaveChanges();
if (feedback.Id != default(int))
{
result.Success = true;
result.Text = "Success";
}
}
else
{
result.Text = "Required Parameters missing.";
}
}
}
catch
{
result.Text = "Error";
}
}
else
result.Text = "Signature or photo missing";
return result;
}
public async Task Post()
{
var模型=新的ApiData();
var result=新结果();
if(Request.Content.IsMimeMultipartContent())
{
尝试
{
字符串root=HttpContext.Current.Server.MapPath(“~/assets/temp”);
var provider=新的MultipartFormDataStreamProvider(根);
var sb=new System.Text.StringBuilder();//保存响应正文
//读取表单数据并返回异步任务。
wait Request.Content.ReadAsMultipartAsync(提供程序);
//这说明了如何获取表单数据。
foreach(provider.FormData.AllKeys中的var键)
{
foreach(provider.FormData.GetValues(键)中的var val)
{
if(key.Equals(“范围”))
model.Scope=val;
if(key.Equals(“Lang”))
model.Lang=val;
if(key.Equals(“集合”))
model.Collection=val;
}
}
如果(!model.Scope.Equals(“反馈”,StringComparison.InvariantCultureIgnoreCase))
result.Text=“缺少范围。”;
其他的
{
var Util=new Utils();
model.Collection=Util.ToString(model.Collection);
var\u Feedback=JsonConvert.DeserializeObject(model.Collection);
尝试
{
//这说明了如何获取上载文件的文件名。
foreach(provider.FileData中的var文件)
{
FileInfo FileInfo=newfileinfo(file.LocalFileName);
字符串BaseUrl=HttpContext.Current.Server.MapPath(“~/assets/feedback/”);
字符串oldFile=file.Headers.ContentDisposition.FileName.TrimStart(“”).TrimEnd(“”);
string NewName=string.Format(“{0}{1}”,Util.NewGuid,Path.GetExtension(oldFile));
if(file.Headers.ContentDisposition.Name.ToLower().Contains(“照片”))
{
_Feedback.Photos=string.IsNullOrEmpty(_Feedback.Photos)?NewName:_Feedback.Photos+“,“+NewName;
fileInfo.MoveTo(BaseUrl+NewName);
}
else if(string.IsNullOrEmpty(_Feedback.Signatures)和&file.Headers.ContentDisposition.Name.ToLower()包含(“签名”))
{
_反馈。签名=新名称;
fileInfo.MoveTo(BaseUrl+NewName);
}
}
}
捕获{}
if(Util.IsRequired(_Feedback.CustomerId)
&&Util.IsRequired(_Feedback.ServiceRequestId)
&&需要使用工具(_反馈。态度)
&&需要使用工具(_反馈。工作道德)
&&需要使用工具(_Feedback.Hygiene)
)
{
var反馈=新反馈()
{
CustomerId=\u Feedback.CustomerId,
ServiceRequestId=\u Feedback.ServiceRequestId,
态度,态度,
工作道德,
卫生,
AmoutPaid=\u Feedback.AmoutPaid,
照片=_Feedback.Photos,
签名=_Feedback.Signatures,
Created=DateTime.UtcNow,
Updated=DateTime.UtcNow
};
db.Feedbacks.Add(反馈);
db.SaveChanges();
if(feedback.Id!=默认值(int))
{
结果:成功=正确;
result.Text=“成功”;
}
}
其他的
{
result.Text=“缺少必需的参数。”;
}
}
}
接住
{
result.Text=“Error”;
}
}
其他的
result.Text=“签名或照片缺失”;
返回结果;
}
这是邮递员的要求
在Fiddler客户端中公开post请求时,我已经看到,当使用html表单post发布时,在多部分/表单数据中存在边界;虽然邮递员和其他客户没有界限
这可能是邮递员
总而言之,如果使用Postman设置内容类型标题,它似乎会覆盖默认浏览器功能,而不会添加边界。大多数情况下,这是一件好事,但对于多部分/表单数据来说并非如此,因为我们需要浏览器为我们添加边界。尝试删除内容类型标题。当发送实际文章时,浏览器将自动添加适当的标题并创建边界
你的