Java 学习篇(文件上传)
在很多项目中 图片上传是必不可少的(其实这不是boot里面的东西 只是我整理到这里面了),既然这常用 很多人也肯定接触到了,那就直接贴代码
package com.boot.controllrt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
@RequestMapping("/file")
public class FileController {
@PostMapping("/add")
public String file(@RequestParam MultipartFile file) {
if (file.isEmpty()) {
System.out.println("文件为空空");
}
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
String filePath = "D://Config"; // 上传后的路径
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath+"/"+fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
String filename = "/Config/" + fileName;
return filename;
}
}
然后用postMan测试(这工具是很强大的接口调试工具)
首先在config文件下没得图片
使用postman测试后config文件下出现了上传的图片
文件上传和视频上传都是同理,因为都是字节流。