我正在尝试使用Java(HTTP发布)上传文件:
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#服务器:
public void ProcessRequest(HttpContext context) {
var uploadedFile = context.Request.Files[0]; // often throws exception with message: "Thread was being aborted."
}
此代码有效-有时。希望有人能帮忙。
最佳答案
看到我不知道会遇到什么错误/异常,因为您正在使用HttpURLConnection
上传文件,所以我建议阅读:
BalusC - How to use java.net.URLConnection to fire and handle HTTP requests?。只需向下滚动即可上传文件。