[Spring MVC]ファイルをアップロードするコード

Javaコード
/**
* ファイルのアップロード
*
* @param request
* @param params
* @param values
* @return
* @throws Exception
*/
public static List<Map<String, Object>> upload(HttpServletRequest request,
String[] params, Map<String, Object[]> values) throws Exception {

List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mRequest.getFileMap();

String uploadDir = request.getSession().getServletContext()
.getRealPath(“/")
+ FileOperateUtil.UPLOADDIR;
File file = new File(uploadDir);

if (!file.exists()) {
file.mkdir();
}

String fileName = null;
int i = 0;
for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()
.iterator(); it.hasNext(); i++) {

Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();

fileName = mFile.getOriginalFilename();

String storeName = rename(fileName);

String noZipName = uploadDir + storeName;
String zipName = zipName(noZipName);

// ファイルの圧縮
ZipOutputStream outputStream = new ZipOutputStream(
new BufferedOutputStream(new FileOutputStream(zipName)));
outputStream.putNextEntry(new ZipEntry(fileName));
outputStream.setEncoding(“GBK");

FileCopyUtils.copy(mFile.getInputStream(), outputStream);

Map<String, Object> map = new HashMap<String, Object>();
// 固定パラメータ
map.put(FileOperateUtil.REALNAME, zipName(fileName));
map.put(FileOperateUtil.STORENAME, zipName(storeName));
map.put(FileOperateUtil.SIZE, new File(zipName).length());
map.put(FileOperateUtil.SUFFIX, “zip");
map.put(FileOperateUtil.CONTENTTYPE, “application/octet-stream");
map.put(FileOperateUtil.CREATETIME, new Date());

// カスタムパラメータの設定
for (String param : params) {
map.put(param, values.get(param)[i]);
}

result.add(map);
}
return result;
}

Java

Posted by arkgame