【发布时间】: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