C# httpclient上传文件

/// <summary>
/// 上传文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost, Route("UploadFile")]
[NonAuthorize]
public async Task<Response<string>> UploadFile(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return ResultBuilder.FailResult("", "文件不存在");
    }
    var requestUrl = $"{CommonConfig.ZFUrl}/special/upload/file";
    // 读取文件
    Stream fileStream = file.OpenReadStream();
    // 实例化multipart表单模型
    var formData = new MultipartFormDataContent();
    // 设定文件类型表单项,使用StreamContent存放文件流
    //文件名不能带中文 Todo后面改成文件id
    string encodedFileName = Uri.EscapeDataString(file.FileName);
    formData.Add(new StreamContent(fileStream), "file", encodedFileName);
    // 实例化HttpClient
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CommonConfig.ZFToken);
    // 发送请求
    HttpResponseMessage result = await _httpClient.PostAsync(requestUrl, formData);
    // 接受结果
    var responseContent = await result.Content.ReadAsStringAsync();
    _log.Info($"文件上传: {responseContent}");

    fileStream.Close();
    return ResultBuilder.SuccessResult("文件上传成功");

}

  

file.FileName文件名不能带中文
posted on 2024-08-09 12:21  程铭  阅读(48)  评论(0编辑  收藏  举报