[英]How to write file to multi-part/formdata http request C# from HTML5 FileAPI
我使用以下代碼嘗試向django后端寫入一個HTTP請求,以將文件從ASP.net 4.5網頁上傳到Web服務,最后返回到我們的api,並且該服務讀取請求,但返回錯誤:“密鑰即使指定了名稱文件,也無法在“中找到'file'。 我應該以其他方式將文件附加到請求嗎? 請求的格式是否正確?
客戶端:
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;
}
解決了編碼和傳遞文件的問題。
首先通過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將對象寫入byte []
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.