Httpclient multipart/form-data 上传图片

Httpclient multipart/form-data pust image

我正在尝试使用 Httpclient.SendAsync 或 Httpclient.PutAsync 发送带有二进制文件的 Put 请求以上传到服务器。但我得到的只是服务器响应中的 400 个错误请求。这是代码

private static HttpResponseMessage Upload()
    {
        var apiUri = string.Format(url);
        string url = (url);

        var message = new HttpRequestMessage();
        message.RequestUri = new Uri(apiUri);
        message.Method = HttpMethod.Put;

        var fileObj = Images.ChooseImageAndToInfoObject();

        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            var filestream = new FileStream(fileObj.filePath, FileMode.Open);

            content.Add(new StreamContent(filestream), fileObj.fileName, fileObj.fileNameWithExtension);
            content.Add(new StringContent("file"), "withName");
            content.Add(new StringContent("string"), "fileName");
            content.Add(new StringContent("image/*"), "mimeType");

            message.Content = content;

            message.Headers.Add("Authorization", MyToken);


            // var res = client.SendAsync(message).Result;
             var response = client.PutAsync(url, content).Result;
            return response;
        }

希望你们,伙计们

是否需要通过multipart-formdata发送文件名和mimetype?如果不尝试将数据作为 StreamContent 发送并通过内容 header:

设置文件名和 mime 类型
private static HttpResponseMessage Upload()
    {
        var apiUri = string.Format(url);
        string url = (url);

        var message = new HttpRequestMessage();
        message.RequestUri = new Uri(apiUri);
        message.Method = HttpMethod.Put;

        var fileObj = Images.ChooseImageAndToInfoObject();

        using (var client = new HttpClient())

        var filestream = new FileStream(fileObj.filePath, FileMode.Open);

        var content = new StreamContent(filestream);
        content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileObj.filePath));
        content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") 
        { 
            Name = "\"files\"", 
            FileName = "\"" + fileName + "\""
        };

        message.Content = content;

        message.Headers.Add("Authorization", MyToken);


        // var res = client.SendAsync(message).Result;
        var response = client.PutAsync(url, content).Result;
        return response;

如果您将文件设置为特定 ID 或通过 Post:

,则通过 PUT 发送内容
var response = client.PostAsync(url, content).Result;