上传10M以下的没有问题,上传10M以上的就无法从服务器获得响应值,这是为什么,http协议如何实现大文件上传
URL url = new URL(ManageConfigUtils.IMG_UPLOAD_PATH);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type",
ContentType.multipart_form_data);
con.setRequestProperty("Charset", "UTF-8");
con.setInstanceFollowRedirects(true);
con.setDoOutput(true);
con.setDoInput(true);
con.setReadTimeout(300 * 1000);
con.setChunkedStreamingMode(1024 * 1024);
con.connect();
StringBuffer buffer = new StringBuffer();
buffer.append("\r\n--LamfireFormBoundaryucJiylDzwZWyoOSF\r\n");
buffer.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getFileName() + "\"\r\n");
buffer.append("Content-Type: application/octet-stream\r\n\r\n");
OutputStream os = new DataOutputStream(con.getOutputStream());
os.write(buffer.toString().getBytes());
InputStream is = file.getFileItem().getInputStream();
byte[] filebuffer = new byte[10240];
synchronized (filebuffer) {
int length = -1;
while (-1 != (length = is.read(filebuffer))) {
os.write(filebuffer, 0, length);
}
}
os.flush();
buffer = new StringBuffer();
buffer.append("\r\n--LamfireFormBoundaryucJiylDzwZWyoOSF\r\n");
buffer.append("Content-Disposition: form-data; name=\"" + "filedir"
+ "\"\r\n");
buffer.append("Content-Type: text/plain;charset=" + "UTF-8"
+ "\r\n\r\n");
buffer.append(dir);
os.write(buffer.toString().getBytes());
os.flush();
os.close();
is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
con.disconnect();
con.setChunkedStreamingMode(1024 * 1024); 这句话的设置问题吧
http协议没有规定post的数据的限制,理论上可以上传任何大的数据,但是 由于http传输大数据时的不稳定,而且会一直占用服务器端的资源,
所以大文件还是建议走 ftp的方式上传,上传完通过http请求通知服务器做业务逻辑。
服务器没有响应,需要看看是服务器一直在处理数据,只是还没有上传完,还是服务器报错了,结合服务器的日志看一下,通常都能发现问题。