springboot配置
#指定图片访问域名
upload:
path: http://localhost:8081/images/uploadImg/
java后端代码
/**
-
@Author:itchenxx
-
文件上传
**/
@RestController
public class UploadController {
//注入图片访问域名
@Value("${upload.path}")
private String uploadPath;/***
-
文件上传
*/
@RequestMapping(value = “/uploadFile”, method = RequestMethod.POST)
public Result fileUpload(MultipartFile file, HttpServletRequest request) throws IOException {String fileName = file.getOriginalFilename(); //获取上传文件的名字
//获取项目的根目录
//在开发测试模式时,得到地址为:{项目跟目录}/target/static/images/upload/
//在打成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
File path=new File(ResourceUtils.getURL(“classpath:”).getPath());String filePath = path + “/static/images/uploadImg/”; //定义上传文件的存放位置
//判断文件夹是否存在,不存在则创建
File fileUpload = new File(filePath);if (!fileUpload.exists()) {
fileUpload.mkdirs();
}String newFilePath = filePath + “/” + fileName; //新文件的路径
try {
file.transferTo(new File(newFilePath)); //将传来的文件写入新建的文件
return new Result(true, uploadPath+fileName);} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return new Result(false, “上传失败”);
}
}
-