我正在尝试使用Java(HTTP Post)上传文件:
HttpURLConnection conn = (HttpURLConnection) new URL(_uploadTarget).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setDoOutput(true);
long fileLength = fileContentLength + tail.length();
String stringData = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"metadata\"\r\n\r\n" + metadata + "\r\n" + "--" + boundary + "\r\nContent-Disposition: form-data; name=\"uploadfile\"; filename=\"" + fileName + "\"\r\nContent-Type: application/octet-stream; charset=UTF-8\r\nContent-Transfer-Encoding: binary\r\n" + "Content-length: " + fileLength + "\r\n\r\n";
long requestLength = stringData.length() + fileLength;
conn.setRequestProperty("Content-length", "" + requestLength);
conn.setFixedLengthStreamingMode((int) requestLength);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead = 0;
byte b[] = new byte[1024];
BufferedInputStream bufin = new BufferedInputStream(
new FileInputStream(_file));
while ((bytesRead = bufin.read(b)) != -1) {
out.write(b, 0, bytesRead);
out.flush();
progress += bytesRead;
}
out.writeBytes(tail);
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
c#server:
public void ProcessRequest(HttpContext context) {
var uploadedFile = context.Request.Files[0]; // often throws exception with message: "Thread was being aborted."
}
此代码有效 - 有时候。希望有人可以提供帮助。
答案 0 :(得分:3)
由于您使用HttpURLConnection
上传文件,因此我不知道您收到了哪些错误/异常,我建议您阅读:
答案 1 :(得分:0)
虽然您的代码示例中缺少一些重要信息,但我认为您的Java部分很好,因为它“有时可以工作”,并且该异常特定于C#。
我不做C#,但是Google会在您的Stackoverflow问题中显示以下链接:http://www.debugging.com/bug/14721。以下是相关摘录:
通过将请求执行超时计时器设置为稍高于2分钟的值来解决它:)
如果请求处理确实需要很长时间,那么您的解决方案可能是将超时设置得更高。