【问题标题】:Uploading file with Java使用 Java 上传文件
【发布时间】:2011-06-04 16:36:36
【问题描述】:

我正在尝试使用 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# 服务器:

public void ProcessRequest(HttpContext context) {
var uploadedFile = context.Request.Files[0]; // often throws exception with message: "Thread was being aborted."
}

此代码有时有效。希望有人能帮忙。

【问题讨论】:

  • 而且它从不向您显示任何类型的......异常?
  • @Riduidel 代码在服务器端脚本中显示“// 经常抛出异常并显示消息:“线程被中止。””。

标签: c# java .net httphandler httpurlconnection


【解决方案1】:

看到我不知道您遇到了什么错误/异常,因为您正在使用 HttpURLConnection 上传文件,那么我建议您阅读:

【讨论】:

    【解决方案2】:

    尽管您的代码示例中缺少一些关键信息,但我认为您的 Java 部分很好,因为它“有时可以工作”并且异常是特定于 C# 的。

    我不使用 C#,但 Google 在以下链接中揭示了您的 Stackoverflow 问题:http://www.debugging.com/bug/14721。以下是相关性摘录:

    通过将请求执行超时计时器设置为略高于 2 分钟的值来解决它:)

    如果请求处理确实需要这么长时间,您的解决方案可能是将超时设置得更高。

    【讨论】:

    • 如果是上传大文件,只需要在web.config文件中配置超时时间和请求长度即可。我正在尝试使用 2 到 50 kb 左右的文件。然而,另一个建议解决了这个问题。我在上面发布的 Java 代码有问题。 :-)
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2015-11-30
    • 2013-08-04
    • 2015-02-11
    • 2010-10-31
    相关资源
    最近更新 更多