springmvc配置文件
<!-- bean扫描-->
<context:component-scan base-package="uploadfile.comtroller"></context:component-scan>
<!-- Thymeleaf视图解析器-->
<bean id="thymeleafViewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
<property name="characterEncoding" value="UTF-8"></property>
<property name="order" value="1"></property>
<property name="templateEngine">
<bean id="thymeleafViewResolver" class="org.thymeleaf.spring6.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
<!--设置模板文件的位置(前缀)-->
<property name="prefix" value="/WEB-INF/templates/"/>
<!--设置模板文件后缀(后缀),Thymeleaf文件扩展名不一定是html,也可以是其他,例如txt,大部分都是html-->
<property name="suffix" value=".html"/>
<!--设置模板类型,例如:HTML,TEXT,JAVASCRIPT,CSS等-->
<property name="templateMode" value="HTML"/>
<!--用于模板文件在读取和解析过程中采用的编码字符集-->
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<!-- 注解驱动-->
<mvc:annotation-driven/>
<!--指定了当用户访问根路径("/")时,将会返回名为"index"的视图-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
web.xml配置
<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-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<!--设置单个支持最大文件的大小-->
<max-file-size>2097152</max-file-size>
<!--设置整个表单所有文件上传的最大值-->
<max-request-size>2097152</max-request-size>
<!--设置最小上传文件大小-->
<file-size-threshold>0</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
前端简单实现
文件上传表单 enctype设置请求头的内容类型
enctype="application/x-www-form-urlencoded" 是默认类型
enctype="multipart/form-data" 文件上传
@{/file/up} 是一个Thymeleaf的URL表达式
type="file" 固定设置
<form th:action="@{/file/up}" method="post" enctype="multipart/form-data">
文件上传:<input type="file" name="fileName"/><br>
<input type="submit" value="上传">
</form>
<a th:href="@{/download}">文件下载</a>
后端实现
@RequestMapping(value = "/file/up",method = RequestMethod.POST)
public String uploadFile(@RequestParam("fileName") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
//获取上传的文件名
String originalFilename = multipartFile.getOriginalFilename();
BufferedInputStream bin = new BufferedInputStream(multipartFile.getInputStream());
String uploadPath = request.getServletContext().getRealPath("upload");
File file = new File(uploadPath);
if(!file.exists()){
file.mkdirs();//创建文件夹
}
//使用UUID避免同名文件 上传覆盖
String destFile = uploadPath + "/" + UUID.randomUUID().toString()+ originalFilename.substring(originalFilename.lastIndexOf("."));
//写出 到服务器
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile,true));
//边读边写
byte [] bytes = new byte[1024*1024];
int count = 0;
while ((count = bin.read(bytes))!=-1){
bos.write(bytes,0,count);
}
bos.flush();
bos.close();
bin.close();
return "OK";
}
@GetMapping("/download")
public ResponseEntity<byte []> downloadFile(HttpServletRequest request) throws IOException {
File file = new File(request.getServletContext().getRealPath("/upload") + "/1.jpg");
//设置响应体
//1.创建响应头
HttpHeaders httpHeaders = new HttpHeaders();
//2.设置响应类型
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//3.设置下载文件名 file.getName() 1.jpg attachment附件
httpHeaders.setContentDispositionFormData("attachment",file.getName());
//下载文件 file.toPath() 文件的绝对路径
return new ResponseEntity<byte []>(Files.readAllBytes(file.toPath()),httpHeaders, HttpStatus.OK);
}