【问题标题】:How to write file to multi-part/formdata http request C# from HTML5 FileAPI如何从 HTML5 FileAPI 将文件写入多部分/表单数据 http 请求 C#
【发布时间】:2014-03-11 13:13:20
【问题描述】:

我使用以下代码尝试向我们的 django 后端写入 http 请求,以将文件从 ASP.net 4.5 网页上传到 web 服务,最后返回到我们的 api,服务读取请求但返回错误: "key 'file' not found in " 即使指定了名称文件。我应该以不同的方式将文件附加到请求中吗?请求格式是否正确?

客户端:

function UploadFileTask(id,tid)
    {

        var Stream = new FileReader();
        var NewFile = document.getElementById("FileIn"+id).files[0];
        Stream.onload = (function (File) {
            LocqusService.AddFileTask($("#DOMgroup").val(), $("#DOMuid").val(), $("#DOMtoken").val(), NewFile.name,new Int8Array(File.target.result), tid, NewFile.type, function (response) {
                if (response.success)
                {
                    $("#FileIn" + id).val("");
                }
                else
                {
                    $("#FileIn" + id).val("");
                }
            }, function () {
                $("#FileIn" + id).val("");
            });
        });
        Stream.readAsArrayBuffer(NewFile);

    }

网络服务

public sendResponse AddFileTask(string gname, int uid, string token, string note, object file, int tid, string fileType)
{
    var fileByte = ObjectToByteArray(file);
    var response = apiFactory.addFileTaskV2(gname,token,uid,fileByte,tid,note, fileType);
    return response;
}

后端

protected static String PostToDBMultiPart(String APIcall, String parameters, byte[] File, string fileType) //post to locqus DB
    {
        String apiResponse;

        try
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://devapi.url.com:9000/api" + APIcall);

            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            timer.Start();
            string boundary = "----bound" + DateTime.Now.Ticks.ToString("x");
            request.Method = "POST";
            var data = new Dictionary<string, string>();

            //parse parameters to name collection
            var preData = HttpUtility.ParseQueryString(parameters);

            //add data to dictionary
            foreach (string key in preData.AllKeys)
            {
                data.Add(key, preData[key]);
            }
            // Set the ContentType property of the WebRequest.
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            var requestStream = request.GetRequestStream();
            var writer = new StreamWriter(requestStream);
            foreach (var item in data)
            {

                var test = (string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", item.Key));
                writer.Write("\r\n--" + boundary + "\r\n");
                writer.Write(test);
                writer.Write(item.Value);
            }
            var head = (string.Format("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", data["note"]));

            writer.Write("\r\n--" + boundary + "\r\n");
            writer.Write(head);
            writer.Write("Content-Type: " + fileType + "\r\n\r\n");
            string end = "\r\n--" + boundary + "--\r\n";
            writer.Write(File);
            writer.Write(end);
            var blah = testing.ToString();

            // Close the Stream object.
            writer.Flush();
            writer.Close();
            // Close the Stream object.
            requestStream.Close();


            var response = request.GetResponse();
            var responseStream = response.GetResponseStream();
            var reader = new StreamReader(responseStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Clean up the streams.

            apiResponse = responseFromServer;
            reader.Close();                
            response.Close();

            timer.Stop();

            TimeSpan timeTaken = timer.Elapsed;
        }
        catch (WebException e)
        {
            string responseFromServer = "";
            apiResponse = "error:" + Environment.NewLine + e.Message;
            if (e.Response != null)
            {
                var reader = new StreamReader(e.Response.GetResponseStream());
                responseFromServer = reader.ReadToEnd();
            }
            return apiResponse;
        }

        return apiResponse;
    }

【问题讨论】:

  • 您可以使用HttpClient来发布多部分内容,而不是处理字符串操作。

标签: c# asp.net django html file-upload


【解决方案1】:

解决了编码和传递文件的问题。

首先通过 readAsDataURL 将文件作为 64 位字符串读取

function UploadFileTask(id,tid)
    {           
        var Stream = new FileReader();
        var NewFile = document.getElementById("FileIn"+id).files[0];
        Stream.onload = (function (File) {
            LocqusService.AddFileTask($("#DOMgroup").val(), $("#DOMuid").val(), $("#DOMtoken").val(), NewFile.name,File.target.result, tid, NewFile.type, function (response) {
                if (response.success)
                {
                    $("#FileIn" + id).val("");
                }
                else
                {
                    $("#FileIn" + id).val("");
                }
            }, function () {
                $("#FileIn" + id).val("");
            });
        });
        Stream.readAsDataURL(NewFile);        
    }

然后我可以将它传递给 Web 服务并使用 Convert.FromBase64String 将对象写入字节 []

public sendResponse AddFileTask(string gname, int uid, string token, string note,String file, int tid, string fileType)
{
    byte[] data = Convert.FromBase64String(file.Split(',')[1]);
    var response = apiFactory.addFileTaskV2(gname,token,uid,data,tid,note, fileType);
    return response;
}

然后最终将请求作为 HttpClient 异步帖子发送出去

protected async static Task<string> PostToDBMultiPart(String APIcall, String parameters, byte[] File, string fileType)
    {
        String apiResponse;
        string responseBodyAsText;
        try
        {
            // Create a request using a URL that can receive a post. 
            string boundary = "----Locqus" + DateTime.Now.Ticks.ToString("x");
           // request.Method = "POST";
            var data = new Dictionary<string, string>();

            //parse parameters to name collection
            var preData = HttpUtility.ParseQueryString(parameters);

            //add data to dictionary
            foreach (string key in preData.AllKeys)
            {
                data.Add(key, preData[key]);
            }

           var client = new HttpClient();
           var content = new MultipartFormDataContent(boundary);     
           //add parameters
           foreach (var item in data)
           {
               content.Add(new StringContent(item.Value), item.Key);
           }
           //add file
            content.Add(new StreamContent(new MemoryStream(File)), "file", data["note"]);

            HttpResponseMessage response = client.PostAsync("https://api.url.com/api"+APIcall, content).Result;
            response.EnsureSuccessStatusCode();
            responseBodyAsText = response.Content.ReadAsStringAsync().Result;
            timer.Stop();

            TimeSpan timeTaken = timer.Elapsed;
            return responseBodyAsText;

        }
        catch (WebException e)
        {
            string responseFromServer = "";
            apiResponse = "error:" + Environment.NewLine + e.Message;
            if (e.Response != null)
            {
                var reader = new StreamReader(e.Response.GetResponseStream());
                responseFromServer = reader.ReadToEnd();
            }
            return apiResponse;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 2018-06-10
    • 2019-10-13
    • 2018-07-18
    相关资源
    最近更新 更多