文件的上传与下载
文件上传下载案例
1、文件上传
1.1 导入依赖
<!-- 文件上传相关依赖 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
1.2 springmvc配置文件中增加文件解析器
<!-- 文件上传解析器,bean的id必须叫 multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000"></property>
</bean>
1.3 handler
@RestController
public class UploadController {
@RequestMapping("/upload")
public String upload(@RequestParam("img") MultipartFile img, HttpSession session){
try {
String originalFilename = img.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); //.jpg
String realPath = session.getServletContext().getRealPath("/files");
System.out.println("-->" + realPath);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
File dest = new File(realPath, uuid.concat(extName));
img.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
1.4 测试
- 上传成功后,在realPath目录下有一个文件。
2、文件下载
2.1 页面
<a href="download?name=gzmn.jpg">下载gzmn.jpg</a>
2.2 Controller
package com.qf.java2007.web.controller;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.OutputStream;
/**
* @author ghy
* @version 1.0
*/
@RestController
public class DownloadController {
@RequestMapping("/download")
public void download(String name, HttpSession session, HttpServletResponse response){
try {
//通过文件名获取到服务器上的真实文件
String filePath = session.getServletContext().getRealPath("/files/" + name);
FileInputStream in = new FileInputStream(filePath);
//告知浏览器以附件的形式去打开这个资源
response.addHeader("content-disposition", "attachment;filename=" + name);
OutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
} catch (Exception e) {
e.printStackTrace();
}
}
}