文件上传和下载接口
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Slf4j
@RequestMapping("/file")
@RestController
public class FileController {
@PostMapping("/upload")
public String upload(MultipartFile file) throws IOException {
log.warn("file => {}", file);
final String filename = file.getOriginalFilename();
final Path rootPath = Paths.get(System.getProperty("user.dir") + File.separator + "files");
if (!Files.exists(rootPath)) {
Files.createDirectory(rootPath);
System.out.println("创建" + rootPath.toString());
}
final Path path = Paths.get(rootPath.toString() + File.separator + filename);
file.transferTo(path);
return filename;
}
@GetMapping("/{fileName}")
public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
final Path path = Paths.get(System.getProperty("user.dir") + File.separator + "files" + File.separator + fileName);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
final WritableByteChannel writableByteChannel = Channels.newChannel(response.getOutputStream());
final FileChannel fileChannel = new FileInputStream(path.toFile()).getChannel();
fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
fileChannel.close();
writableByteChannel.close();
}
}
测试上传
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传">
</form>
下载就直接使用localhost:你的端口/file/要下载的文件名字