Spring MVC Tips
[Spring][Spring MVC]
コントローラー
リクエストパラメータを必須でなくする
@RequestMapping(value="/test.html",method = RequestMethod.GET)
public String setupForm( @RequestParam(value="id", required=false) String id, ModelMap model) {
:
ファイルアップロード
- MultipartFile を利用する
- 文字化け対策をする
- Form
<form id="formUpload" action="upload.html" method="POST" enctype="multipart/form-data" > <input name="attach_file" /> <input type="submit" value="アップロード"/> </form>
- 文字コードをiso-8859-1として変換
@RequestMapping(value="/upload.html", method = RequestMethod.POST)
public String uploadFile(MultipartFile file) {
String filename = new String(file.getOriginalFilename().getBytes("iso-8859-1"),"utf-8");
ファイルダウンロード
//String fileName = new String(originalFileName.getBytes("utf-8"),"iso-8859-1"); // Chrome OK, IE NG
String fileName = new String(originalFileName.getBytes("ms932"),"iso-8859-1"); // Chrome OK, IE OK
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "filename=\"" + fileName + "\"");
BufferedInputStream bis = new BufferedInputStream(attachFileDownloadService.getAttachFileOutputStream(attachFileInfo));
os = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) >= 0) {
os.write(buffer,0, len);
}
bis.close();

YAGI Hiroto (piroto@a-net.email.ne.jp)
twitter http://twitter.com/pppiroto
Copyright© 矢木 浩人 All Rights Reserved.