Springboot项目在IDEA中可以正常运行,正常加载图片。但打包部署无法加载图片
背景
- 配置文件
reggie: path: photo/
- 与文件上传相关的类
import com.itheima.reggist.commen.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
@Value("${reggie.path}")
private String basePath; //="D:\java\download\"; //注意这个路径不要写死,要认真听
@PostMapping("/upload")
public R upload(MultipartFile file) {
//获取原始文件名称
String originalFilename = file.getOriginalFilename();
String[] split = originalFilename.split("//.");
String fileName = UUID.randomUUID().toString() + split[split.length - 1];
//创建一个目录对象
File dir = new File(basePath);
if (!dir.exists()) {
dir.mkdirs();
}
//将临时文件转存至指定位置
try {
file.transferTo(new File(basePath + fileName));
} catch (IOException e) {
e.printStackTrace();
}
return R.success(fileName);
}
@GetMapping("/download")
public void download(String name, HttpServletResponse response) {
try {
//输入流,读取文件内容
FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
//输出流,将文件会写给浏览器
ServletOutputStream outputStream = response.getOutputStream();
//设置响应的内容
response.setContentType("image/jpeg");
int len = 0;
byte[] bytes = new byte[2048];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();//刷新一下
}
outputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
//返回R会报如下错误
// HttpMessageNotWritableException: No converter for [class com.itheima.reggist.commen.R] with preset Content-Type 'image/jpeg'
}
}
- 报错信息
java.io.FileNotFoundException: photof966a38e-0780-40be-bb52-5699d13cb3d9.jpg (系统找不到指定的路径。)
查找资料
- 主要的问题就是打包后的java项目的路径发生改变,然后找不到文件
解决方案
在jar所属层级新建一个包(这个包要与配置文件中的包同名),将图片等资料上传至该包即可
- 举例:



