文章目录
文件上传
1 前端代码
<form action="http://127.0.0.1:8080/upload" enctype="multipart/form-data" method="post">
上传文件<input type="file" name="multipartFile"/>
<input type="submit" value="上传"/>
</form>
2 路径配置
server:
port: 8080
file-path: ./appData/
3 Controller
@Value("${file-path}")
private String path;
@Autowired
HttpServletRequest request;
/**
* 文件上传
*
* @param multipartFile
* @return
*/
@PostMapping("/upload")
private String upLoad(MultipartFile multipartFile) {
if (multipartFile != null) {
String originalFilename = multipartFile.getOriginalFilename();
File filePath = new File(request.getServletContext().getRealPath(path) + File.separator + originalFilename);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
try {
multipartFile.transferTo(filePath);
return "upload success";
} catch (IOException e) {
e.printStackTrace();
}
}
return "upload failed";
}
4 外部访问配置ResourceHandler
/**
* @author: Curiosity
* @Date: 2020/11/1 14:24
* @Description:
*/
@Configuration
/**
* lombok为所有final 变量生成构造方法与Spring配合进行注入
*/
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
/**
* final 构造器注入
*/
final ConfigurableEnvironment configurableEnvironment;
final ServletContext servletContext;
@Value("${file-path}")
private String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 获取真实路径
String realPath = servletContext.getRealPath(filePath);
// 添加句柄 http://127.0.0.1:8080/file/git.md
registry.addResourceHandler("/file/**")
// 添加文件真实路径
.addResourceLocations("file:" + realPath)
.setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
}
}
文件下载
1 Controller
@GetMapping("/down/{fileName}")
private ResponseEntity<Resource> downLoad(@PathVariable String fileName) {
File file = new File(request.getServletContext().getRealPath(path) + File.separator + fileName);
if (!file.exists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
try {
Path path = Paths.get(file.getAbsolutePath());
HttpHeaders headers = new HttpHeaders();
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
return ResponseEntity.ok()
.contentLength(file.length())
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
完整代码
1 WebConfig
@Configuration
/**
* lombok为所有final 变量生成构造方法与Spring配合进行注入
*/
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
/**
* final 构造器注入
*/
final ConfigurableEnvironment configurableEnvironment;
final ServletContext servletContext;
@Value("${file-path}")
private String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 获取真实路径
String realPath = servletContext.getRealPath(filePath);
// 添加句柄 http://127.0.0.1:8080/file/git.md
registry.addResourceHandler("/file/**")
// 添加文件真实路径
.addResourceLocations("file:" + realPath)
.setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
}
}
2 UpLoadAndDownLoadController
/**
* @author: Curiosity
* @Date: 2020/11/1 09:52
* @Description:
*/
@RestController
public class UpLoadAndDownLoadController {
@Value("${file-path}")
private String path;
@Autowired
HttpServletRequest request;
/**
* 文件上传
*
* @param multipartFile
* @return
*/
@PostMapping("/upload")
private String upLoad(MultipartFile multipartFile) {
if (multipartFile != null) {
String originalFilename = multipartFile.getOriginalFilename();
File filePath = new File(request.getServletContext().getRealPath(path) + File.separator + originalFilename);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
try {
multipartFile.transferTo(filePath);
return "upload success";
} catch (IOException e) {
e.printStackTrace();
}
}
return "upload failed";
}
@GetMapping("/down/{fileName}")
private ResponseEntity<Resource> downLoad(@PathVariable String fileName) {
File file = new File(request.getServletContext().getRealPath(path) + File.separator + fileName);
if (!file.exists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
try {
Path path = Paths.get(file.getAbsolutePath());
HttpHeaders headers = new HttpHeaders();
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
return ResponseEntity.ok()
.contentLength(file.length())
.headers(headers)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
3 Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>