文件的上传
MultipartFile类中已经封装好解析request等操作 直接通过MultipartFile类进行接收就可以了
upload 为文件组件的name
upload.getOriginalFilename(); 获取文件的名字
upload.transferTo(file);//把文件存放的地址给他
Controller类中的
Multi 多种
part 部分
transfer 转移
@RequestMapping("uploade")public String Uploade(MultipartFile upload) throws IOException {String filename = upload.getOriginalFilename();String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();File file = new File(path,filename);upload.transferTo(file);return "index.jsp";}
配置文件中配置
<bean id="multipartResolver" //id是底层设定好的不可以改class="org.springframework.web.multipart.commons.CommonsMultipartResolver">//如果文件太大需要设置缓存区的大小//<property name="maxUploadSize" value="1024000"></property></bean>
多文件上传
public RespBean addImage(MultipartRequest request) throws IOException {
Map<String, MultipartFile> fileMap = request.getFileMap();
List imgList = new ArrayList();
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/static";
String LinuxPath = "/var/static/";
for (Map.Entry<String, MultipartFile> file : fileMap.entrySet()) {
MultipartFile file1 = file.getValue();
String imgName = UUID.randomUUID().toString() + ".jpg";
// file1.transferTo(new File(path, imgName));
file1.transferTo(new File(LinuxPath, imgName));
imgList.add(imgName);
}
return RespBean.success("图片上传成功", imgList);
}
前端
<form action="uploade" method="post" enctype="multipart/form-data">
<input type="file" name="upload">
<input type="submit" value="上传">
</form>
文件的下载
原生更简单
@RequestMapping("downLoade")
public ResponseEntity<byte[]> downLoade(String filename) throws IOException {
String path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
File file = new File(path,filename);
filename = new String(filename.getBytes("utf-8"),"ISO-8859-1");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attrachment",filename);
byte[] b = FileUtils.readFileToByteArray(file);
return new ResponseEntity(b,headers, HttpStatus.CREATED);
}
