这几天因为项目需要,写一个通过文件流下载文件的东西。整个过程需要一个后台服务器和一个GUI的程序,GUI做下载操作。
URLConnection conn = url.openConnection();
int contentLength = conn.getContentLength();
System.out.println("########## length = " + contentLength);
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream(saveFile);
byte[] buffer = new byte[10240];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.print(bytesum);
fs.write(buffer, 0, byteread);
long downloadPercent = bytesum * 100 / contentLength ;
MainClass.dwProgressBar.setValue((int)downloadPercent); //进度值
System.out.println(" ; percents: " + downloadPercent);
}
fs.close();
GUI端的下载便做好了。
String filePath = getServletContext().getRealPath(File.separator) + "mptd" + File.separator + path
+ File.separator + sName + File.separator;
System.out.println(filePath);
String fileName = new File(filePath).list()[0];
File file = new File(filePath + fileName);
System.out.println(file.getAbsolutePath());
System.out.println(file.isFile());
FileInputStream fis = new FileInputStream(file);
PrintWriter out = response.getWriter();
int b = 0;
while ((b = fis.read()) != -1) {
out.write(b);
}
response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
response.setHeader("Content-Length","" + file.length());
fis.close();
out.close();
服务器端的下载代码也就这样。
好了,我们可以愉快的玩耍了
...
咦,怎么回事儿?下载不动啊,GUI客户端下载,文件长度为-1,下载进度一直都为负数。
折腾半天,原来问题在服务器端的这两句话:
response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
response.setHeader("Content-Length","" + file.length());
这两句话一定要放在文件读写之前,放在读写之后就不起作用了。所以改成下面这样就好了:
String filePath = getServletContext().getRealPath(File.separator) + "mptd" + File.separator + path
+ File.separator + sName + File.separator;
System.out.println(filePath);
String fileName = new File(filePath).list()[0];
File file = new File(filePath + fileName);
response.setHeader("Content-Disposition","attachment;filename=\"" + URLEncoder.encode(fileName,"utf-8") + "\"");
response.setHeader("Content-Length","" + file.length());
System.out.println(file.getAbsolutePath());
System.out.println(file.isFile());
FileInputStream fis = new FileInputStream(file);
PrintWriter out = response.getWriter();
int b = 0;
while ((b = fis.read()) != -1) {
out.write(b);
}
fis.close();
out.close();
好了,现在真的可以愉快的玩耍了。