spring boot后台
package com.example.fileupdown.controller;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.stream.Collectors;
/**
* 文件上传、下载、删除、查询
* @author stefan
*/
@RestController
public class FileController {
private final String fileBaseDirector = "h:\\testFile\\";
private final Path fileBasePath;
public FileController(){
//Path.of(fileBaseDirector)方法亦可
this.fileBasePath = Paths.get(fileBaseDirector);
}
/**
* 图片上传
* @param file
* @return
*/
//@RequestMapping("/uploadFile")
@PostMapping("/uploadFile")
public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file){
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path path = Paths.get(fileBaseDirector + fileName);
try {
Files.copy(file.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(true);
}
/**
* 图片下载
* @param fileName
* @return
*/
@GetMapping("/downloadFile/{fileName}")
public ResponseEntity downloadFile(@PathVariable String fileName){
Path path = fileBasePath.resolve(fileName);
Resource resource = null;
try {
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
/**
* 删除文件
* @param fileName
* @return
*/
@DeleteMapping("/delete/{fileName}")
public ResponseEntity deleteFile(@PathVariable String fileName){
Path deletePath = fileBasePath.resolve(fileName);
Boolean isDelete = Boolean.FALSE;
try {
isDelete = FileSystemUtils.deleteRecursively(deletePath);
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(isDelete);
}
/**
* 获取所有文件
* @return
*/
@GetMapping("/loadAll")
public ResponseEntity loadAll(){
List<String> urlAll = null;
try {
urlAll = Files.walk(fileBasePath,1).filter(path -> !path.equals(fileBasePath))
.map(path -> MvcUriComponentsBuilder.fromMethodName(FileController.class,"downloadFile",path.getFileName().toString())
.build().toString())
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(urlAll);
}
/**
* 图片上传
* @param file
* @throws Exception
*/
@RequestMapping("/upload")
public void upload(@RequestParam("file")MultipartFile file) throws Exception{
//如果没有设置路径,默认保存至根目录
String filePath = file.getOriginalFilename();
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
}
/**
* 图片下载
* @return
* @throws Exception
*/
@RequestMapping("/download")
public ResponseEntity download() throws Exception{
FileSystemResource file = new FileSystemResource("迪丽热巴 - 48.jpg");
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename=123.jpg");
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
}
图片上传过大处理方式:application.properties配置文件添加以下配置
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB
有的版本不一样配置不一样
spring.http.multipart.enabled=true
spring.http.multipart.max-file-size=50MB
spring.http.multipart.max-request-size=50MB
postman测试方式:
- Headers中添加如下图中配置:[{“key”:“Content-Type”,“value”:“multipart/form-data”,“description”:"",“enabled”:true}]
- Body中添加如下图配置[{“key”:“file”,“value”:{“0”:{}},“description”:"",“type”:“file”,“enabled”:true}],注意key值file后面选择file
- 下载中选择send下拉里面的选项
- 有些方法需要注意选择DELETE
js测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片上传</title>
<script src="./../js/jquery-3.5.1.min.js"></script>
</head>
<body>
<div>
<input type="file" accept="image/*" onchange="upload(this)">
</div>
<script>
function upload(e){
debugger;
var file = e.files[0];
var formData = new FormData();
formData.append("file",file);
$.ajax({
url : "http://127.0.0.1:8080/upload",
type : "post",
contentType : false,
dataType : "json",
processData : false,
data : formData,
mimeType : "multipart/form-data",
success : function(result){
console.log(true);
},
error : function(result){
console.log(false);
}
});
}
</script>
</body>
</html>