springMVC实现多文件上传

<h2>上传多个文件 实例</h2>
<form action="/workreport/uploadMultiFile.html" method="post" enctype="multipart/form-data">
<p>
选择文件:<input type="file" name="files">
<p>
选择文件:<input type="file" name="files">
<p>
选择文件:<input type="file" name="files">
<p>
<input type="submit" value="提交">
</form>
   // 多文件上传
@RequestMapping(value = "/uploadMultiFile")
public String uploadMultiFile(HttpServletRequest request) {
try {
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// get the parameter names of the multipart files contained in this request
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next());
String basePath = "F:/testDir/";
for (MultipartFile multipartFile : multipartFiles) {
String fileName = multipartFile.getOriginalFilename();
if (StringUtils.isNotEmpty(fileName)) {
multipartFile.transferTo(new File(basePath + fileName));
}
}
}
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "test/success";
}

以下是以文件流的形式保存上传的文件:

    // 文件上传
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFile(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartHttpServletRequest.getFile("file");
String fileName = file.getOriginalFilename();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String path = "F:/" + simpleDateFormat.format(new Date()) + fileName.substring(fileName.lastIndexOf("."));
OutputStream fileOutputStream = new FileOutputStream(path);
InputStream inputStream = file.getInputStream();
byte[] buffer = new byte[2048];
while (inputStream.read(buffer) != -1) {
fileOutputStream.write(buffer);
}
log.info(path);
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
return "test/success";
}

注:使用springMVC进行多文件的效率显然要比字符流写入方式效率上要高

上一篇:mysql之创建数据库,创建数据表


下一篇:第三节 ISBN 码 / ISSN 码