【发布时间】:2015-10-27 18:38:17
【问题描述】:
我正在尝试使用 java 在浏览器中下载文件。问题是我在代码中没有任何错误。但该文件未在浏览器中下载。 我已经转发了这个网站:http://www.codejava.net/frameworks/spring/spring-mvc-sample-application-for-downloading-file。
ServletContext context = request.getServletContext();
String appPath = context.getRealPath("");
String filePat="pat of the file";
File downloadFile = new File(filePath);
System.out.println("downloadFile path: "+ filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
System.out.println("buffer: "+ buffer.length);
int bytesRead = -1;
// write bytes read from the input stream into the output stream
int counter=0;
while ((bytesRead = inputStream.read(buffer))!=-1 ) {
counter++;
System.out.println("counter: "+ counter+ "bytesRead:"+bytesRead);
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
【问题讨论】:
-
代码有两个幻数,写代码坏了。如果我是你,我会从其他网站复制/粘贴代码。
-
我添加了 1895 只是为了检查。由于计数器值 > 1896 给出了 writebeyondcontent 长度错误。
标签: java spring servlets httpresponse