简体   繁体   中英

File upload via multipart-form-data using WebClient in C#

有人可以告诉我如何在multipart-form-data中上传文件,这样我就可以添加post-params和file作为内容。

If you need both files and objects in the payload you can use a multipart form like this:

Form

<form id="createForm" method="post" enctype="multipart/form-data" action="http://localhost:5000/api/send">
<input type="text" name="Field1"  id="field1" />
<input type="text" name="Field2"  id="field2" />
<input type="file" id="bulk" name="Bulk" required />
</form>

POCO

class MyClass
{
  public string Field1{get;set;}
  public string Field2{get;set;}
}

Controller
In the controller you can access the files using Request.Form.Files which gives you a collection with all your uploaded files.Then you can read your file(s) using a StreamReader like i do below:

[HttpPost]
[Route("api/send")]
[DisableRequestSizeLimit] 
public async Task<long> CreateAsync(MyClass obj) {
{
  var file=this.Request.Form.Files[0];  //there's only one in our form
  using(StreamReader reader=new StreamReader(file))
  {
    var data=await reader.ReadToEndAsync();
    Console.WriteLine("File Content:"+data);
    Console.WriteLine("{ Field1 :"+obj.Field1.ToString()+",Field2:"+obj.Field2.ToString()+"}");
  }

}

Caution
Take care when dealing with multipart since you will also need to specify the maximum size of a segment.
That is done in the Startup :

public void ConfigureServices(IServiceCollection services) {
    services.Configure<FormOptions>(options => {
                    options.ValueCountLimit = 200;
                    options.ValueLengthLimit = int.MaxValue;
                    options.MultipartBodyLengthLimit = long.MaxValue;
                });
 }

or like i did it directly in the Controller -s method , by decorating it with [DisableRequestSizeLimit] attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM