[英]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: 如果您需要有效负载中的
files
和对象,则可以使用如下所示的multipart
表单:
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 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: 在控制器中,您可以使用
Request.Form.Files
访问文件,它会为您提供包含所有上传文件的集合。然后您可以使用StreamReader
读取您的文件,如下所示:
[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. 处理
multipart
时要小心,因为您还需要指定段的maximum
大小。
That is done in the Startup
: 这是在
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. 或者我喜欢直接在
Controller
-s方法中使用[DisableRequestSizeLimit]
属性进行装饰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.