Webapi Sending HTML form data: File uploads and multipart MIME

Source: Internet
Author: User
Tags httpcontext unsupported


5.3 Sending HTML Form Data
5.3 Sending HTML form data (2)


This article quoted: http://www.cnblogs.com/r01cn/archive/2012/12/20/2826230.html



by Mike wasson| June 21, 2012
Mike Wasson | date: 2012-6-21


Part 2:file Upload and Multipart MIME
Part 2nd: File uploads and multipart MIME


This tutorial shows how to upload files to a Web API. It also describes how to process multipart MIME data.
This tutorial shows how to upload a file to the Web API. It also describes how to handle multipart MIME data.



Download the completed project.
Download the full project.



Example of an HTML form for uploading a file:
The following is an HTML form for uploading a file (5-8):


<form name= "Form1" method= "Post" enctype= "Multipart/form-data" action= "Api/upload" >    <div>        < Label For= "caption" >image caption</label>        <input name= "caption" type= "text"/>    </div>    <div>        <label for= "Image1" >image file</label>        <input name= "Image1" type= "File"/ >    </div>    <div>        <input type= "Submit" value= "Submit"/>    </div></form >


Figure 5-8. File Upload Form



This form contains a text input control and a file input control. When a form contains a file input control, the enctype attribute should always be "multipart/form-data", which Specifies that the form would be sent as a multipart MIME message.
This form has a text input control and a file input control. When a form contains a file input control, its enctype Tag property should always be "multipart/form-data", which indicates that the form will be sent as a multipart MIME message.



The format of a multipart MIME message is easiest to understand by looking at an example request:
By examining a sample request, it is easy to understand the format of the multipart (multipart) MIME message:


POST http://localhost:50460/api/values/1 http/1.1user-agent:mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) gecko/20100101 firefox/12.0accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q= 0.8accept-language:en-us,en;q=0.5accept-encoding:gzip, Deflatecontent-type:multipart/form-data; boundary=---------------------------41184676334content-length:29278
-----------------------------41184676334content-disposition:form-data; Name= "caption"
Summer vacation-----------------------------41184676334content-disposition:form-data; Name= "Image1"; Filename= "Grandcanyon.jpg" Content-type:image/jpeg
(binary data not shown) (binaries, not listed)-----------------------------41184676334--


This message was divided into the parts, one for each form control. Part boundaries is indicated by the lines so start with dashes.
This message is divided into two parts (parts) for each form control. The part boundary is indicated by a line that starts with some dashes.



The part boundary includes a random component ("41184676334") to ensure, the boundary string does not accidentally app Ear inside a message part.
The part boundary contains a random component ("41184676334") to ensure that the boundary string does not accidentally appear in the message part.



Each message part contains one or more headers, followed by the part contents.
Each message part contains one or more headers followed by the contents of the part.


    • The content-disposition header includes the name of the control. For files, it also contains the file name.
      The Content-disposition (Content layout) header includes the control name. For a file, it also includes the file name.
    • The Content-type header describes the data in the part. If the header is omitted, the default is Text/plain.
      The Content-type (content Type) header describes the data in the part. If the header is ignored, the default is Text/plain (text format).


The previous example, the user uploaded a file named Grandcanyon.jpg, with content type image/jpeg; The value of the text input was "Summer Vacation".
In the previous example, the user uploads a file named Grandcanyon.jpg, whose content type is image/jpeg, and the text input box has a value of "Summer Vacation".


File Upload
File Upload


Now let's look at a WEB API controller this reads files from a multipart MIME message. The controller would read the files asynchronously. Web API supports asynchronous actions using the Task-based programming model. First, here's the code if you are targeting. NET Framework 4.5, which supports the async and await keyw Ords.
Now let's examine the controller that reads the file from a multi-part MIME message. The controller will read the file asynchronously. The Web API supports the use of the task-based programming model (this is about. NET Parallel Programming MSDN Documentation-Translator note) "for asynchronous actions. First, the following is code for the. NET Framework 4.5, which supports the async and await keywords.


Using system.diagnostics;using system.net;using system.net.http;using system.threading.tasks;using System.Web;using System.Web.Http;
public class uploadcontroller:apicontroller{Public async task


Notice that the controller action does not take any parameters. That ' s because we process the request body inside the action, without invoking a media-type formatter. Note that the Controller action does not take any parameters. This is because we are dealing with the request body in action and do not have to call the Media-type formatter.



The ismultipartcontent method checks whether the request contains a multipart MIME message. If not, the controller returns HTTP status code 415 (Unsupported Media Type). The ismultipartcontent method checks whether the request contains a multipart MIME message. If not, the controller returns an HTTP status code of 415 (Unsupported media type).



The Multipartformdatastreamprovider class is a helper object, allocates file streams for uploaded files. To read the multipart MIME message, call the Readasmultipartasync method. This method extracts all of the message parts and writes them to the streams provided by the Multipartformdatastream Provider. The Multipartformdatastreamprovider class is an helper object that allocates file streams for uploaded files. To read a multipart MIME message, you call the Readasmultipartasync method. The method extracts all the message parts and writes them to the stream provided by Multipartformdatastreamprovider .



When the method completes, you can get information about the files from the FileData property, which is a collect Ion of Multipartfiledataobjects. When the method is complete, you can about the file through the FileData property, which is a collection of multipartfiledata objects.


    • Multipartfiledata.filename is the local file name in the server, where the file was saved. Multipartfiledata.filename is a local file name on the server where this file is saved.
    • multipartfiledata.headers contains the part header (not the request header). You can use this to access the content_disposition and Content-type headers. multipartfiledata.headers contains the part header (not the request header). You can use it to access the content_disposition and Content-type headers.


As the name suggests, Readasmultipartasync is an asynchronous method. To perform the completes of the method, use a continuation task (. NET 4.0) or the await keyword (. NET 4.5). As the name implies,Readasmultipartasync is an asynchronous method. In order to perform some work after the method completes, you need to use the continuation (continue) task (. NET 4.0) or the await keyword (. NET 4.5).



The. NET Framework 4.0 version of the previous code: The following is the. NET Framework version 4.0 of the aforementioned code:


Public task
Reading Form Control Data
Reading form Control Data


The HTML form that I showed earlier had a text input control. The HTML form shown earlier has a text input control.


    <div>        <label for= "caption" >image caption</label>        <input name= "caption" type= "text"/ >    </div>


You can get the value of the the control from the FormData property of the Multipartformdatastreamprovider.
The value of the control can be obtained by Multipartformdatastreamprovider the FormData property.


 Public Async task


FormData is a namevaluecollection this contains name/value pairs for the form controls. The collection can contain duplicate keys. Consider this form:
FormData is a namevaluecollection(name/value collection) that contains the name/value pairs of the form controls. The collection may contain duplicate keys. Consider the following form (5-9):


<form name= "Trip_search" method= "post" enctype= "Multipart/form-data" action= "Api/upload" > <div> < Input type= "Radio" name= "Trip" value= "round-trip"/> round-trip </div> <div> <input t Ype= "Radio" name= "Trip" value= "one-way"/> One-way </div>
<div> <input type= "checkbox" name= "Options" value= "nonstop"/> Only show non-stop flights &lt ;/div> <div> <input type= "checkbox" name= "Options" value= "airports"/> Compare nearby Airp Orts </div> <div> <input type= "checkbox" name= "Options" value= "dates"/> My travel D Ates is flexible </div>
<div> <label for= "seat" >seating preference</label> <select name= "Seat" > & Lt;option value= "Aisle" >Aisle</option> <option value= "window" >Window</option> &        Lt;option value= "center" >Center</option> <option value= "None" >no preference</option> </select> </div></form>


Figure 5-9. Forms with Duplicate keys



The request body might look like this:
The request body might look like this:


-----------------------------7dc1d13623304d6content-disposition:form-data; Name= "Trip"
Round-trip-----------------------------7dc1d13623304d6content-disposition:form-data; Name= "Options"
Nonstop-----------------------------7dc1d13623304d6content-disposition:form-data; Name= "Options"
Dates-----------------------------7dc1d13623304d6content-disposition:form-data; Name= "Seat"
Window-----------------------------7dc1d13623304d6--


In this case, the FormData collection would contain the following key/value pairs:
In this case, the Formdata collection will contain the following "key/value" pairs:


        • Trip:round-trip
        • Options:nonstop
        • Options:dates
        • Seat:window


Webapi Sending HTML form data: File uploads and multipart MIME


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.