【问题标题】:How to upload a file on a server through api call in asp.net mvc如何通过asp.net mvc中的api调用在服务器上上传文件
【发布时间】:2020-07-13 20:09:02
【问题描述】:

public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
    var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
    WebClient webClient = new WebClient();
    byte[] responseBinary = webClient.UploadFile(apiUrl, file.FileName);
    string response = Encoding.UTF8.GetString(responseBinary);
    /* Giving error here. How to proceed?
}

我想上传一个文件到这个url,响应如上图所示。如何在 C# 中进一步处理相同的问题?请帮忙

【问题讨论】:

  • 尝试使用 fiddler 在客户端和服务器之间的通信中达到峰值。可能会提示发生了什么问题(例如,发送数据的方式存在问题,或者 http 错误代码在 fiddler 中比尝试调试更容易解释)。请发布结果。
  • 使用 api 调用上传文件的简单方法是将文件转换为 base64 字符串并在服务器上发送字符串,然后在服务器端将 base64 字符串转换为文件并存储在目录中。

标签: asp.net asp.net-mvc rest asp.net-mvc-4 asp.net-web-api


【解决方案1】:

试试下面的代码。

public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
    var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
    
    using (HttpClient client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            byte[] fileBytes = new byte[file.InputStream.Length + 1];                         
            file.InputStream.Read(fileBytes, 0, fileBytes.Length);
            var fileContent = new ByteArrayContent(fileBytes);
            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
            content.Add(fileContent);
            var result = client.PostAsync(apiURL, content).Result;
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return new 
                {
                    code = result.StatusCode,
                    message = "Successful",
                    data = new 
                    {
                        success = true,
                        filename = file.FileName
                    }
                };
            }
            else
            {
                return new 
                {
                    code = result.StatusCode,
                    message = "Error"
                };
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 2011-01-08
    • 2011-06-22
    • 1970-01-01
    • 2020-01-14
    • 2021-12-10
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多