且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用Flurl发布`multipart/form-data`

更新时间:2022-02-18 22:26:34

根据规格(日期为2011年6月),建议同时发送filenamefilename*以获得最大兼容性:

According the spec (dated June 2011), sending both filename and filename* is recommended for maximum compatibility:

在此规范之前的许多用户代理实现都没有 了解"filename *"参数.因此,当两个文件名" 和文件名*"出现在单个标头字段值中,收件人 应该选择文件名*"而忽略文件名".这样,发件人可以 通过发送更多的消息,避免使用特殊外壳的特定用户代理 富有表现力的文件名*"参数,而文件名"参数为 后备收件人的回退.

Many user agent implementations predating this specification do not understand the "filename*" parameter. Therefore, when both "filename" and "filename*" are present in a single header field value, recipients SHOULD pick "filename*" and ignore "filename". This way, senders can avoid special-casing specific user agents by sending both the more expressive "filename*" parameter, and the "filename" parameter as fallback for legacy recipients.

如果filename*实际上是导致对 fail 的调用,则服务器遵循HTTP规范确实存在问题.另外,将namefilename用引号引起来是非常不规范的.

If filename* is actually causing the call to fail, there's a real problem with the server adhering to the HTTP spec. Also, enclosing name and filename in quotes is very non-standard.

也就是说,Flurl的快捷方式涵盖了90%的情况,但是您始终可以使用基础的HttpClient API来涵盖这种不寻常的情况.在这种情况下,我认为您需要手动构建内容,以便处理那些Content-Disposition标头:

That said, Flurl's shortcuts cover the 90% cases, but you can always use the underlying HttpClient APIs to cover unusual cases like this one. In this case I think you need to build up the content manually so you can deal with those Content-Disposition headers:

var mpc = new MultipartContent();
var sc = new StringContent("value");
sc.Headers.Add("Content-Disposition", "form-data; name=\"some-label\"");
mpc.Add(sc);
var fc = new StreamContent(fs);
fc.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"my-filename.txt\"");
mpc.Add(fc);

然后您可以将其与Flurl一起使用,如下所示:

Then you can use it with Flurl like this:

var response = await "http://target-host.com"....PostAsync(mpc);