[英]How to upload files and submit form data using Web API?
Background 背景
I currently have working C# code to read the values in a HTTP POST form submission from a webpage. 我目前可以使用C#代码从网页读取HTTP POST表单提交中的值。 It looks like this:
看起来像这样:
public class CompanyDTO
{
public string CompanyName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZIP { get; set; }
}
// POST: api/Submission
public HttpResponseMessage Post(CompanyDTO Company)
{
return JsonToBrowser("{'location':'" + Company.City + "," + Company.State + "'}");
}
I also have working code to read attachments from a file upload control on a page: 我也有工作代码可以从页面上的文件上传控件中读取附件:
// POST: api/Submission
public HttpResponseMessage Post()
{
// Process and save attachments/uploaded files
var folderName = "App_Data";
var PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
});
return fileInfo;
});
return JsonToBrowser("{'status':'success'}");
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
Obviously there is a bit more to the last piece of code, but I hope it at least illustrate my issue. 显然,最后一段代码还有更多内容,但是我希望至少可以说明我的问题。
My problem 我的问题
I am now trying to combine these two pieces of code. 我现在正在尝试将这两段代码结合起来。 I thought it would be as easy as putting the data transfer object in the Post function:
我认为这就像将数据传输对象放入Post函数一样简单:
public HttpResponseMessage Post(CompanyDTO Company)
This results in the following being returned to the browser when I perform the HTTP POST: 当执行HTTP POST时,这将导致以下内容返回到浏览器:
{ "Message":"The request entity's media type 'multipart/form-data' is not supported for this resource.", "ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'CompanyDTO' from content with media type 'multipart/form-data'.", "ExceptionType":"System.Net.Http.UnsupportedMediaTypeException", "StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\\r\\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\\r\\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" }
{“ Message”:“此资源不支持请求实体的媒体类型'multipart / form-data'。”,“ ExceptionMessage”:“没有MediaTypeFormatter可用于从媒体类型的内容中读取'CompanyDTO'类型的对象'multipart / form-data'。“,” ExceptionType“:” System.Net.Http.UnsupportedMediaTypeException“,” StackTrace“:”在System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型,IEnumerable1 System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content,Type type,IEnumerable1 formatters,IFormatterLogger formatterLogger,CancellationToken cancellingToken)\\ r \\ n在System.Web.Http.ModelBinding上的formatters,IFormatterLogger formatterLogger,CancellationToken cancelleToken)\\ r .FormatterParameterBinding.ReadContentAsync(HttpRequestMessage请求,类型类型,IEnumerable1格式化程序,IFormatterLogger格式化程序Logger,CancellationToken取消令牌)“}
My Question 我的问题
So how do I both upload one or more files and read/process the regular form data fields using C# and ASP.NET. 因此,我如何使用C#和ASP.NET上传一个或多个文件并读取/处理常规表单数据字段。 I am using Visual Studio 2013 (Community Edition).
我正在使用Visual Studio 2013(社区版)。 Also, I am a beginner in C#, so I may need some extra hints/help if you refer to a function/class about where to find it.
另外,我是C#的初学者,因此如果您引用有关在哪里找到它的函数/类,则可能需要一些额外的提示/帮助。
The closest SO question I found related to this issue is How to submit form-data with optional file data in asp.net web api but it does not have any response/answer... 我发现与此问题最接近的SO问题是如何在asp.net Web API中提交带有可选文件数据的表单数据,但是它没有任何响应/答案。
Here's my solution when I encountered this issue: 这是我遇到此问题时的解决方案:
Client: 客户:
public async Task UploadImage(byte[] image, string url)
{
Stream stream = new System.IO.MemoryStream(image);
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
Uri resourceAddress = null;
Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
request.Content = streamContent;
var httpClient = new Windows.Web.Http.HttpClient();
var cts = new CancellationTokenSource();
Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
}
Controller: 控制器:
public async Task<HttpResponseMessage> Post()
{
Stream requestStream = await this.Request.Content.ReadAsStreamAsync();
byte[] byteArray = null;
using (MemoryStream ms = new MemoryStream())
{
await requestStream.CopyToAsync(ms);
byteArray = ms.ToArray();
}
.
.
.
return Request.CreateResponse(HttpStatusCode.OK);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.