无法使用HttpURLConnection上传文件

时间:2011-04-29 14:41:34

标签: java httpurlconnection

我一直在使用HttpURLConnection上传文件,但在执行时我收到如下错误:

  

请求被拒绝,因为没有找到多部分边界

以下是我的代码段

File importFile = new File(args[0]);
url = new URL("http://localhost:8888/ajax/import?action=csv&session=" + sessionId + "&folder=36");
URLConnection uc = url.openConnection();
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Cookie", cookieStringBuffer.toString());
connection.setRequestProperty("content-type", "multipart/form-data");
connection.setDoOutput(true);
connection.connect();

FileInputStream is = new FileInputStream(importFile);
OutputStream os = connection.getOutputStream();
PrintWriter pw = new PrintWriter(os);
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = is.read(buffer)) != -1) {
   //os.write(buffer, 0, bytes_read);
   pw.print(buffer); // here we "send" our body!
}
pw.flush();
pw.close();

如何解决问题?

2 个答案:

答案 0 :(得分:0)

将文件复制到输出流的代码是错误的,删除行

PrintWriter pw = new PrintWriter(os);

而不是使用pw,用正确的读取字节数写入os,

os.write(buffer, 0 bytes_read);

答案 1 :(得分:0)