springmvc实现文件的上传和下载
一、需要的依赖
<!--web程序的发动机servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!--上传和下载的第三方依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
二、基本的配置
-
servlet的配置
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
-
springmvc配置
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <property name="maxUploadSize" value="409600"></property> <property name="defaultEncoding" value="utf-8"></property> </bean> <!-- 注解驱动--> <mvc:annotation-driven conversion-service="conversionService2"/>
备注:备注注解驱动一方面是为了使用注解简化开发,另一方面是为了让spring自动为我们生成处理器映射器和处理器适配器
三、文件的下载实现
//1、设置响应头
HttpHeaders httpHeaders = new HttpHeaders();
//2、设置响应内容呈现方式(attachment:附件)
httpHeaders.setContentDispositionFormData("attachment","文件名");
//3、设置响应内容的格式
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//4、封装响应的主体
new ResponseEntity<>(byte[],httpHeaders, HttpStatus.OK);
四、文件的上传
- 使用MultipartFile来接收上传的文件对象
- 实现
//1、校验上传的文件对象是否有效
if (file.isEmpty() || file.getSize() == 0) {
return getWrongRseult("please upload attachment file");
}
//2、获取文件名
String filename = file.getOriginalFilename();
//3、修改文件在磁盘的存储名(可选操作)
//获取文件的扩展名
String extendname = filename.substring(filename.lastIndexOf("."));
//解决文件上传名字重复的问题
String finalName = UUID.randomUUID().toString().replace("-", "") + extendname;
//3、设置文件存储的位置
String path = "F:\\项目静态资源测试";
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory()) {
return getWrongRseult("the file upload is failed");
}
String finalPath = path + "\\" + finalName;
//4、出文件到磁盘
file.transferTo(new File(finalPath));