「Java開発」SpringMVCでファイルダウンロードを実現する方法
Javaコード:
package com.sniper.springmvc.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sniper.springmvc.utils.ValidateUtil;
@Controller
public class FileDownloadAction extends RootAction {
// mime//application/vnd_startnews24.ms-excelダウンロード
private String contentType = “application/vnd_startnews24.ms-excel";
private String fileName;
private String filePath;
public String getFileName() throws UnsupportedEncodingException {
fileName = filePath.substring(filePath.lastIndexOf(“/") + 1);
String Agent = request.getHeader(“User-Agent");
if (null != Agent) {
Agent = Agent.toLowerCase();
if (Agent.indexOf(“firefox") != -1) {
fileName = new String(fileName.getBytes(), “iso8859-1");
} else if (Agent.indexOf(“msie") != -1) {
fileName = URLEncoder.encode(fileName, “UTF-8");
} else {
fileName = URLEncoder.encode(fileName, “UTF-8");
}
}
return fileName;
}
/**
* redirect:downloadでファイルパスやファイルタイプを転送
*
* @param path
* @param type
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = “download")
public ResponseEntity<byte[]> download(
@RequestParam(value = “path") String path,
@RequestParam(value = “type", required = false) String type)
throws IOException {
// メンバー変数の値を設定
this.filePath = path;
if (ValidateUtil.isValid(contentType)) {
this.contentType = type;
}
HttpHeaders headers = new HttpHeaders();
byte[] body = null;
HttpStatus httpState = HttpStatus.NOT_FOUND;
File file = new File(path);
if (file.exists() && file.isFile()) {
InputStream is = new FileInputStream(file);
body = new byte[is.available()];
is.read(body);
is.close();
headers.add(“Content-Type", this.contentType);
headers.add(“Content-Length", “" + body.length);
headers.add(“Content-Disposition", “attachment;filename="
+ getFileName());
httpState = HttpStatus.OK;
}
ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers,
httpState);
return entity;
}
}