前端代码的实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<fieldset>
<legend>文件上传</legend>
<form action="param/upload" method="post" enctype="multipart/form-data">
头像:<input type="file" name="uploadFile"><br>
<input type="submit" value="提交">
</form>
</fieldset>
</body>
</html>
后端代码实现(上传,下载)
/**
* 注意:uploadFile 一定要和 表单页面的 name属性值重名
*/
@Controller
@RequestMapping("/param")
public class fileUpload {
@RequestMapping("/upload")
@ResponseBody
/**
* 注意:uploadFile 一定要和 表单页面的 name属性值重名
*/
public void fileUpload(MultipartFile uploadFile, HttpServletRequest request) {
//获取被上传文件的 原始名称
String originalFilename = uploadFile.getOriginalFilename();
//准备接受被上传文件的位置 (指的是 tomcat /工程的路径)
// D://xxxx/upload123.png
//String realPath = request.getSession().getServletContext().getRealPath("upload");
String realPath = "D:\\Download\\";
//如果当前目录不存在 则创建
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
//避免重名 时间 或者 随机数
String filename = realPath + File.separator + System.currentTimeMillis() + originalFilename;
try {
uploadFile.transferTo(new File(filename)); //上传
} catch (IOException e) {
e.printStackTrace();
}
}
// 文件下载
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename) throws Exception {
// 下载路径
//String path = request.getServletContext().getRealPath("/upload");
String path = "D:\\Download\\";
File file = new File(path + File.separator + filename);
HttpHeaders headers = new HttpHeaders();
// 解决中文乱码
String downloadfile = new String(filename.getBytes("UTF-8"), "iso-8859-1");
// 以下载方式打开文件
headers.setContentDispositionFormData("attachment", downloadfile);
// 二进制流
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
}
pom文件
<!--文件上传的jar包-->
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
文件上传的配置
<!--文件上传 , id必须为:multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--上传的属性 , 根据实际需求配置-->
<!--配置文件上传的总大小 ,100M-->
<property name="maxUploadSize" value="104857600"></property>
<!--限制 每次上传的文件只能10M以下-->
<property name="maxUploadSizePerFile" value="10485760"></property>
<!--指定编码-->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
|