SpringMVC文件下载与上传
1、文件下载
(1)服务器控制器
package com.ssm.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
@Controller
public class FileUpAndDowController {
@RequestMapping("/test/down")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
ServletContext servletContext = session.getServletContext();
String realPath = servletContext.getRealPath("image/");
realPath = realPath+ File.separator+"ddp.jpg";
InputStream is = new FileInputStream(realPath);
byte[] bytes = new byte[is.available()];
is.read(bytes);
MultiValueMap<String, String> headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=ddp1.jpg");
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers,
statusCode);
is.close();
return responseEntity;
}
}
(2)客户端连接
<a th:href="@{/test/down}">下载图片</a>
2、文件上传
(1)客户端链接
<form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo"><br>
<input type="submit" value="上传">
</form>
(2)服务器控制器
@RequestMapping("/test/up")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
String fileName = photo.getOriginalFilename();
String substring = fileName.substring(fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString();
fileName = uuid+substring;
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("image");
File file = new File(photoPath);
if (file.exists()) {
file.mkdir();
}
String finaPath = photoPath + File.separator + fileName;
photo.transferTo(new File(finaPath));
return "success";
}
(3)SpringMVC配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
(4)pom.xml文件配置
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>