Java中资料的上传与下载

时间:2023-03-08 17:39:26

1.导架包

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

2.配置ssm.xml文件

<!--配置上传文件-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="#{10*1024*1024}"></property>
</bean>
<!--设置静态资源的访问-->
<mvc:resources mapping="/upload/**" location="/upload/"></mvc:resources>
<mvc:annotation-driven></mvc:annotation-driven>

3.前端提交上传表单

<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="保存">
</form>

4.处理上传请求

 @RequestMapping("upload")
public String addbook(MultipartFile myfile,HttpServletRequest request) {
String path=request.getRealPath("/uploadimage");//要保存文件的文件夹
try {
myfile.transferTo(new File(path+"/"+myfile.getOriginalFilename()));//复制
} catch (IOException e) {
e.printStackTrace();
}
request.setAttribute("filename",myfile.getOriginalFilename());//return "redirect:/book/getbooklist";
}

5.前端下载请求

<a href="down?fname=汪达尔.jpg">下载</a>

6.处理下载请求

@RequestMapping("down")
public ResponseEntity down(HttpServletRequest request,String fname){
String path = request.getRealPath("/upload");
System.out.println(path);
File f= new File(path+"/"+fname);
HttpHeaders h =new HttpHeaders();
h.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> res = null;
try {
h.setContentDispositionFormData("attachment", URLEncoder.encode(fname,"utf-8"));
res = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),h, HttpStatus.CREATED);
} catch (IOException e) {
e.printStackTrace();
} return res;
}