springboot jar包运行文件上传及显示
2018-08-19 本文已影响18人
大大大浣熊
文件上传是在web开发中所遇到的比较常见的需求了,常见的文件上传有几种
- 一是将文件上传到oss等类似的文件服务器上,然后在数据库中保存相应的文件地址,上传有对应的sdk,地址直接就是一个http地址,这种方式下的文件上传及显示比较简单,但是成本较大。
- 另一种就是将文件上传到项目路径的静态资源文件夹resources/下,这种方式比较方便,也比较省成本。在Springboot还未流行的时候,我们一般是用tomcat来运行一个web项目,这时候将文件上传到资源文件夹下没什么问题。但是springboot推荐使用jar包的方式来运行(如果是在idea中直接运行,非jar包,则没有半点问题),这时候再将文件上传到resources文件夹下就会有问题,会提示文件路径不存在。因为resource的文件操作是依赖于文件系统的,将项目打成一个独立jar包后是没有resource这个文件夹的,解压jar包就知道了。那么这时候我想要上传文件到服务器上怎么办呢,Springboot提供了一个静态资源的映射方式,你可以添加一个外部文件夹并将其作为一个静态资源文件夹的映射,也就是说添加这个映射后你可以在项目中像访问静态资源文件夹一样来访问外部的文件夹。具体怎么做呢,添加一个类就够了,上代码。
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Value("${my.upload.imgPath}")
private String path;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String staticMapping="/image/**";
String localDirectory = "file:"+path;
registry.addResourceHandler(staticMapping).addResourceLocations(localDirectory);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
就这么几行代码,其中localDirectory变量是外部文件夹,文件需要上传到该文件夹中去,staticMapping就是映射的静态资源请求路径了。
比如说
localDirectory="/usr/file/image";(如果是windows下就"D://file/image")
staticMapping="/image/**"
文件上传到localDirectory中后直接通过http://localhost:8080/image/xx.png即可拿到文件。
下面把controller也一起贴出来吧
@Controller
@RequestMapping(value = "index")
public class IndexController {
@Value("${my.upload.imgPath}")
private String imgPath;
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String upload(HttpServletRequest request){
//上传文件时可能会带普通的参数,这样可以直接拿到
String name = request.getParameter("name");
//可能会有多个文件同时上传
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
BufferedOutputStream stream = null;
for (MultipartFile f : files) {
if (f.isEmpty()){
continue;
}
try {
byte[] b = f.getBytes();
String fileName = f.getOriginalFilename();
// String path = "src/main/resources/uploadFile/";
// String path = imgPath+fileName;
String path = "/Users/halo/Documents/HtmlProject/"+fileName;
stream = new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(b);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
@RequestMapping("hello")
public String indexController(Model model){
model.addAttribute("imgsrc", "/image/34.jpg");
return "index";
}
}