package training.guojiang.coterie.api;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.hibernate.loader.entity.NaturalIdEntityJoinWalker;
import org.springframework.util.ResourceUtils;
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 training.guojiang.coterie.vo.UploadImage;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
@RestController
@RequestMapping("upload")
public class UploadController {
/**
* 上传文件
* @param file
* @return
*/
@PostMapping("/image")
public UploadImage uploadImage(@RequestParam(name = "file")MultipartFile file, HttpServletRequest request) throws IOException {
//检查文件的大小
long size = file.getSize();
if (size>1 * 1024 * 1024){
throw new RuntimeException("上传失败!上传的文件大小超出了限制!");
}
//检查文件的类型
String contentType = file.getContentType();
List<String> types = new ArrayList<String>();
types.add("image/jpeg");
types.add("image/png");
types.add("image/gif");
if (!types.contains(contentType)) {
throw new RuntimeException("上传失败!不允许上传此类型的文件!");
}
//获取原始的文件名:
String originalFilename = file.getOriginalFilename();
int lastIndexOf = originalFilename.lastIndexOf(".");
//获取文件的后缀
String suffix = originalFilename.substring(lastIndexOf - 1);
String fileName=UUID.randomUUID().toString()+suffix;
//判断文件夹是否存在:不存在创建
/**
* 这里遇到的问题
* 1:相对路径和绝对路径区别:项目一般都使用相对路径防止项目迁移资源丢失
*
*2:resources目录下的资源不会经行编译,需要进行手动编译才能访问到。
*
* 3:访问静态资源时访问路径不需要加static: http://localhost:8000/upload/"+fileName
*
* 4:由于内嵌tomacat所以 request.getServletContext().getRealPath()
* 这种方式不能拿到resource的相对路径。
*/
//String upload1 =ResourceUtils.getURL("classpath:").getPath()+"/static/upload";//这里是获取target/classes/static/upload路径
String c = System.getProperty("user.dir");//这里是获取项目的相对路径
String upload1=c+"\\src\\main\\resources\\static\\upload";
File upload=new File(upload1);
if(!upload.exists()&&!upload.isDirectory()){
System.out.println("不存在");
upload.mkdirs();
System.out.println("创建成功");
}
//保存文件
File dest=new File(upload,fileName);
file.transferTo(dest);
Map<String,String> map=new HashMap();
map.put("path",fileName);
map.put("url","http://localhost:8000/upload/"+fileName);
return UploadImage.builder().status(true).message("上传成功").data(JSONObject.toJSONString(map)).build();
}
}
这里遇到了很多关于相对路径和绝对路径的获取方法和注意事项