1.加入jar包commons-fileupload-1.2.1.jar
commons-io-2.0.jar
2.springmvc.xml中配置bean
<bean id="nultipartResolver"
class="org.springframework.web.multipart.commons.commonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>
3.前台页面
<form action="testFileUpload" method="POST" enctype="multipart/form-data">
File: <input type="file" name="file"/>
Desc: <input type="text" name="desc"/>
<input type="submit" value="Submit"/>
</form>
4.在cotroller中
private String savePicture(MultipartFile file, Date date, String path, int i) {
int index = file.getOriginalFilename().lastIndexOf(".");
String filePostfix = file.getOriginalFilename().substring(index);
String fileName = date.getTime() + "-" + i + filePostfix;
String dbPath = path.substring(path.lastIndexOf("upload"));
String filePath = dbPath + "/" + fileName;
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
private List<String> uploadPictures(MultipartFile[] files) {
String path = WebConf.getValue("PROVIDER_INFO_CONFIRM");
Date date = new Date();
path += new SimpleDateFormat("yyyy/MM/dd").format(date).toString();
List<String> filePath = new ArrayList<>();
int i = 0;
for (MultipartFile file : files) {
filePath.add(savePicture(file, date, path, i++));
}
LOG.debug("filePath{}", filePath);
return filePath;
}
文件下载
@RequestMapping("/testResponseEntity")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
byte [] body = null;
ServletContext servletContext = session.getServletContext();
InputStream in = servletContext.getResourceAsStream("/files/abc.txt");
body = new byte[in.available()];
in.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=abc.txt");
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
springmvc文件上传下载
最新推荐文章于 2024-04-15 11:34:31 发布