多文件上传(表单提交)
前端文件上传方式为表单提交,后端用 HttpServletRequest 接收,如果需要携带参数前端也正常携带,后台通过request.getParameter(“name”)获取。
前端代码:
<form action="/xx/file" method="post" enctype="multipart/form-data">
<input type="intro" name="intro" /><br />
<input type="file" name="filelist" /><br />
<input type="file" name="filelist" /><br />
<input type="file" name="filelist" /><br />
<input type="submit" value="提交"/><br />
</form>
后端代码:
@RequestMapping("/file")
public ModelAndView file(HttpServletRequest request) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("Intro", request.getParameter("intro"));
jsonObject.put("commTol", HttpServletFileUtil.getFileJon(request));
return new ModelAndView();
}
保存文件工具类
public class HttpServletFileUtil {
private static String FILEPATH_SYS = "";
private static String FILEPATH = "";
public static String getFileJon(HttpServletRequest request) {
TimeStamp timeStamp = new TimeStamp();
String fileJon = "";
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartHttpServletRequest.getFiles("filelist");
Iterator<MultipartFile> iterator = files.iterator();
while (iterator.hasNext()) {
MultipartFile file = iterator.next();
if (file != null && file.getSize() > 0) {
try {
String filedes = StringUtils.join(timeStamp.getUUID() + ".jpg");
String filepath = StringUtils.join(FILEPATH + filedes);
String filepathSys = StringUtils.join(FILEPATH_SYS + filedes);
if (StringUtils.isBlank(fileJon)) {
fileJon = StringUtils.join(fileJon, filepathSys);
} else {
fileJon = StringUtils.join(fileJon + ",", filepathSys);
}
File sa = new File(filepath);
file.transferTo(sa);
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
throw new Exception("相关图片不能为空");
}
return fileJon;
}
}
|