无法使用 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();
如何纠正该问题?
I've been using HttpURLConnection to upload a file but on execution I get an error like:
request was rejected because no multipart boundary was found
Following is my code snippet
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();
How can I correct the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将文件复制到输出流的代码是错误的,删除该行
并使用正确的读取字节数写入操作系统,而不是使用 pw,
Your code to copy file to the output stream is wrong, remove the line
and instead of using pw, write to os with the correct count of bytes read,
您需要分段文件上传: http://www.theserverside.com/news/ 1365153/HttpClient-and-FileUpload
提供的链接示例:
You need Multipart File upload: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
Example from the link provided: