「Java開発」SpringMVCでファイルをダウンロードするソースコード
Javaコード
@RequestMapping(params = “downfile")
public void downfile(HttpServletRequest request,HttpServletResponse response) throws Exception{
Long fileID = ServletRequestUtils.getLongParameter(request, “id", 0);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
String result = “";
if(null != fileID){
UserFiles userFiles = this.userFileDao.findObject(fileID);
if(userFiles !=null){
File downFiles = new File(userFiles.getFileCurrPath()+userFiles.getFileName()+"."+userFiles.getFileType());
if(!downFiles.exists()){
return;
}
try {
fis = new FileInputStream(downFiles);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
ServletUtils.setFileDownloadHeader(request,response, userFiles.getFileName()+"."+userFiles.getFileType());
int byteRead = 0;
byte[] buffer = new byte[8192];
while((byteRead=bis.read(buffer,0,8192))!=-1){
bos.write(buffer,0,byteRead);
}
bos.flush();
fis.close();
bis.close();
fos.close();
bos.close();
} catch (Exception e) {
log.info(“ダウンロード失敗した……");
}
}
}
}
public static void setFileDownloadHeader(HttpServletRequest request,HttpServletResponse response, String fileName) {
try {
String encodedfileName = null;
String agent = request.getHeader(“USER-AGENT");
if(null != agent && -1 != agent.indexOf(“MSIE")){//IE
encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8″);
}else if(null != agent && -1 != agent.indexOf(“Mozilla")){
encodedfileName = new String (fileName.getBytes(“UTF-8″),"iso-8859-1″);
}else{
encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8");
}
response.setHeader(“Content-Disposition", “attachment; filename=\"" + encodedfileName + “\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}