springboot⽂件上传保存路径的问题
⽬录
springboot⽂件上传保存路径
配置代码如下
Springboot上传⽂件的问题(上传到本地⽂件夹中)
先建⽴⼀个controller包
静态资源⽬录如下
springboot⽂件上传保存路径
最近使⽤springboot整合富⽂本编辑器,在整合的时候,对于图⽚上传时候保存路径出现了⼀些问题,代码如下
@PostMapping("/upload")
public Result upload(MultipartFile[] file, HttpServletRequest request) throws IOException {
Result result = new Result();
String path = ServletContext().getRealPath("/public/image/upload");
System.out.println(file.length);
for (MultipartFile f : file) {
String name = f.getOriginalFilename();
}
return result;
}
报了如下异常
java.io.IOException: java.io.FileNotFoundException: C:\Users\22374\AppData\Local\Temp\
tomcat-docbase.262090075120668420.9003\public\image\upload\demo0.png (系统不到指定的路径。)
我到了相应路径下查看,路径下确实没有这些⽂件,因为springboot直接以jar包的⽅式直接运⾏,应该是jar包运⾏时⽣成的相关路径,并没有深⼊研究原理。这⾥并不像tomcat下部署那样,⽂件夹确实存在,并且可读取。所以只能采⽤其他⽅案。
在我们在tomcat下做⽂件上传时候,我们也并不会直接在项⽬下⾯的相关路径下保存上传的⽂件,因为如果这样保存,项⽬重新部署,⽂件就没了。通常是配置tomcat,映射⼀个静态⽂件夹,⽤来存放上传的⽂件,这样在项⽬升级重新部署,⽂件依然存在。现在要解决的问题是,如何使⽤springboot配置静态⽂件夹。
配置代码如下
spring:
mvc:
static-path-pattern: /**
resources:
static-locations:
- classpath:/META-INF/resources/
- classpath:/static
- classpath:/resources/
- file:${upload-path}
upload-path: F:/Java/upload/
关键的代码就是file:${web.upload-path},这个file是配置⼀个⽂件路径做作为静态资源映射,⽽upload-path: F:/Java/upload/是配置路径的实际位置。其余的代码,因为⾃⼰重新配置静态资源映射,所以默认配置失效,⾃⼰要重新配置⼀下。
当然除了配置⽂件配置,还可以⾃⼰继承WebMvcConfigurerAdapter类来配置静态资源映射,当然这是低版本的springboot,⾼版本的继承WebMvcConfigurerationSupport实现。
Springboot上传⽂件的问题(上传到本地⽂件夹中)
先建⽴⼀个controller包
如图所⽰:
FileUploadController.java代码如下所⽰:
ller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile, HttpServletRequest req) {
String realPath = Session().getServletContext().getRealPath("/uploadFile/");
String format = sdf.format(new Date());
String file = realPath + format;
File folder = new File(realPath + format);
if(!folder.isDirectory()) {
folder.mkdirs();
}
String oldName = OriginalFilename();
String newName = UUID.randomUUID().toString() +
oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
// ⽂件保存操作
return file;
spring怎么读取jar文件} catch (IOException e) {
e.printStackTrace();
}
return "上传失败!";
}
}
这⾥我们是上传在了默认⽂件夹⾥⾯,
我的是
这个⽂件夹下。
当然你也可以根据⾃⼰的意愿放在⾃⼰想要的⽂件下⾯,此时需要改变以上的⼀点代码()://file 这⾥是我⾃⼰想要的⽂件夹
String file = "E:\\IDEA01\\学习springboot\\springboot_uploadfiles\\src\\main\\resources\\static\\uploadFile"; File folder = new File(file);
此时会出现上传的⽂件
静态资源⽬录如下
因为主要是演⽰上传⽂件,所以HTML⽂件⽐较简陋
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。