如何在没有文件的情况下使用 MultipartContent?
How to use MultipartContent without file?
[HttpPost]
[Route("Profile")]
public async Task<IHttpActionResult> SubmitPhotos()
{
// Check if the request contains multipart/form-data. // shivam agarwal
if (!Request.Content.IsMimeMultipartContent())
{
ModelState.AddModelError("MIME not supported", "MIME not supported");
return BadRequest();
}
string root = HttpContext.Current.Server.MapPath("~/Content/ProfileImages/");
var provider = new MultipartFormDataStreamProvider(root);
try
{
var newResponse = await Request.Content.ReadAsMultipartAsync(provider);
// pleae check here
//provider=new FormDataCollection(Request.Content);
if (provider.FormData.GetValues("UserId").First() == null || provider.FormData.GetValues("UserId").First() == "")
{
return BadRequest("UserId is required");
}
else if (provider.FormData.GetValues("DisplayName").First() == null || provider.FormData.GetValues("DisplayName").First() == "")
{
return BadRequest("DisplayName is required");
}
foreach (MultipartFileData fileData in provider.FileData)
{
// Image saving process
model.ImageKey = keyvalue[0];
// call business function
if (!response.Exceptions.Any())
{
//saving to database
return Ok(resultResponse);
}
}
return Ok();
}
catch (System.Exception e)
{
ModelState.AddModelError("Exception", e.Message);
return BadRequest();
}
finally
{
FlushTempFiles();
}
}
我正在使用 webapi 将表单集合值提交到数据库。主要输入是 File(Photo),Displayname,UserID 用户从移动应用程序提交三个输入,它将图像保存到文件夹中,将其他两个值保存到数据库中。到现在一切都很好
我的问题是:在我的情况下,文件输入是可选的,所以实际情况是他们可能上传也可能不上传文件输入 (Filedata)
所以,我在这一行中遇到错误
var newResponse = await Request.Content.ReadAsMultipartAsync(provider);
MIME 多部分流意外结束。 MIME 多部分消息不完整。
我已经阅读了将 \r\n 添加到流中的答案,但它在我的情况下不起作用。请告诉我你的意见我怎样才能处理可选文件输入并只获取 userid 和 displayname?
的值
我想你只需要检查你的移动客户端应用程序。如果您的移动应用是Android应用,那么您可以参考以下示例代码:
如果使用 OkHttp:
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
// .addPart(
// Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"myfilename.png\""),
// RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
.build();
final Request request = new Request.Builder()
.url("http://myserver/api/files")
.post(requestBody)
.build();
如果使用Volley,可以参考My GitHub sample,那里要注意
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
我在 Web API 上的调试屏幕,你可以看到 FileData.Count 是 0:
更新:
IMO,您还应该阅读以下内容:
Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart
MIME
在那里,你会发现:
通过查看示例请求最容易理解多部分 MIME 消息的格式:
POST http://localhost:50460/api/values/1 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------41184676334
Content-Length: 29278
-----------------------------41184676334
Content-Disposition: form-data; name="caption"
Summer vacation
-----------------------------41184676334
Content-Disposition: form-data; name="image1"; filename="GrandCanyon.jpg"
Content-Type: image/jpeg
(Binary data not shown)
-----------------------------41184676334--
因此,如果您的客户端应用程序没有发送最后一个 -----------------------------41184676334--
,例如,您的 Web API 将抛出 Unexpected end of MIME multipart stream. MIME multipart message is not complete.
[HttpPost]
[Route("Profile")]
public async Task<IHttpActionResult> SubmitPhotos()
{
// Check if the request contains multipart/form-data. // shivam agarwal
if (!Request.Content.IsMimeMultipartContent())
{
ModelState.AddModelError("MIME not supported", "MIME not supported");
return BadRequest();
}
string root = HttpContext.Current.Server.MapPath("~/Content/ProfileImages/");
var provider = new MultipartFormDataStreamProvider(root);
try
{
var newResponse = await Request.Content.ReadAsMultipartAsync(provider);
// pleae check here
//provider=new FormDataCollection(Request.Content);
if (provider.FormData.GetValues("UserId").First() == null || provider.FormData.GetValues("UserId").First() == "")
{
return BadRequest("UserId is required");
}
else if (provider.FormData.GetValues("DisplayName").First() == null || provider.FormData.GetValues("DisplayName").First() == "")
{
return BadRequest("DisplayName is required");
}
foreach (MultipartFileData fileData in provider.FileData)
{
// Image saving process
model.ImageKey = keyvalue[0];
// call business function
if (!response.Exceptions.Any())
{
//saving to database
return Ok(resultResponse);
}
}
return Ok();
}
catch (System.Exception e)
{
ModelState.AddModelError("Exception", e.Message);
return BadRequest();
}
finally
{
FlushTempFiles();
}
}
我正在使用 webapi 将表单集合值提交到数据库。主要输入是 File(Photo),Displayname,UserID 用户从移动应用程序提交三个输入,它将图像保存到文件夹中,将其他两个值保存到数据库中。到现在一切都很好
我的问题是:在我的情况下,文件输入是可选的,所以实际情况是他们可能上传也可能不上传文件输入 (Filedata)
所以,我在这一行中遇到错误
var newResponse = await Request.Content.ReadAsMultipartAsync(provider);
MIME 多部分流意外结束。 MIME 多部分消息不完整。
我已经阅读了将 \r\n 添加到流中的答案,但它在我的情况下不起作用。请告诉我你的意见我怎样才能处理可选文件输入并只获取 userid 和 displayname?
的值我想你只需要检查你的移动客户端应用程序。如果您的移动应用是Android应用,那么您可以参考以下示例代码:
如果使用 OkHttp:
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
// .addPart(
// Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"myfilename.png\""),
// RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
.build();
final Request request = new Request.Builder()
.url("http://myserver/api/files")
.post(requestBody)
.build();
如果使用Volley,可以参考My GitHub sample,那里要注意
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
我在 Web API 上的调试屏幕,你可以看到 FileData.Count 是 0:
更新:
IMO,您还应该阅读以下内容:
Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME
在那里,你会发现:
通过查看示例请求最容易理解多部分 MIME 消息的格式:
POST http://localhost:50460/api/values/1 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=---------------------------41184676334
Content-Length: 29278
-----------------------------41184676334
Content-Disposition: form-data; name="caption"
Summer vacation
-----------------------------41184676334
Content-Disposition: form-data; name="image1"; filename="GrandCanyon.jpg"
Content-Type: image/jpeg
(Binary data not shown)
-----------------------------41184676334--
因此,如果您的客户端应用程序没有发送最后一个 -----------------------------41184676334--
,例如,您的 Web API 将抛出 Unexpected end of MIME multipart stream. MIME multipart message is not complete.