如何使用 flurl 在 uwp 中 post multipart/form-data

How to post multipart/form-data in uwp using flurl

我在 uwp 中使用 flurl,并想 post 一个图像文件到服务器。

服务器api需要一个参数"image_file",一个二进制文件,需要post使用multipart/form-data。

现在我有了一个StorageFile,如何post呢?

string res = "";
        try
        {
            res = await _detect_api_url
                   .PostMultipartAsync(mp => mp
                   .AddStringParts(new { api_key = _api_key, api_secret = _api_secret, return_landmark = returnLandmarks, return_attributes = returnAttributes })
                   .AddFile("image_file", imageFile)
                   ).ReceiveString();
        }
        catch (FlurlHttpTimeoutException)
        {
            Debug.WriteLine("FlurlHttp internal time out.");
            res = "FlurlHttp internal time out.";
        }
        catch (FlurlHttpException ex)
        {
            Debug.WriteLine(ex.Message);
            res = ex.Call.ErrorResponseBody;
        }

Now I have a StorageFile, how to post it?

AddFile有两种重载方法:

public CapturedMultipartContent AddFile(string name, Stream stream, string fileName, string mediaType = null, int bufferSize = 4096);
public CapturedMultipartContent AddFile(string name, string path, string mediaType = null, int bufferSize = 4096);

这样你就可以为post文件的方法提供文件流或文件本地路径到服务器。如何从StorageFile please reference this article. And for the local file path you can directly get it by StorageFile.Path property. Pay attention that you cannot directly provide a local path build by yourself, you must get it from a StorageFile object, details about this please reference File access permissions.

中读取文件流

以下是通过 AddFile 方法 posting 文件的示例代码。

string _detect_api_url = "http://localhost/BackgroundTransferSample/Upload.aspx";
private async void btntest_Click(object sender, RoutedEventArgs e)
{
    StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/picture0.png"));
    IBuffer buffer = await Windows.Storage.FileIO.ReadBufferAsync(imageFile);
    string res = "";
    try
    {
        //AddFile by file stream.
        res = await _detect_api_url
               .PostMultipartAsync(mp => mp
               .AddFile("image_file", buffer.AsStream(), "imagefile.png", null, (int)buffer.Length)
               ).ReceiveString();

        //AddFile by local file path.
        //res = await _detect_api_url
        //     .PostMultipartAsync(mp => mp
        //     .AddFile("image_file", imageFile.Path)
        //     ).ReceiveString();
    }
    catch (FlurlHttpTimeoutException)
    {
        Debug.WriteLine("FlurlHttp internal time out.");
        res = "FlurlHttp internal time out.";
    }
    catch (FlurlHttpException ex)
    {
        Debug.WriteLine(ex.Message);
        res = ex.Call.ErrorResponseBody;
    }
}