springboot 项目实现文件上传,显示,下载,打包为项目实现文件上传,显示,下载,打包为jar
文件上传是Web中常见的功能,选择性也很多,比如将文件上传到oss等类似的文件服务器上,这种方式成本比较高。文件的上传和显示操作比较简单。另外就是在文件上传到项目
路径的静态资源文件夹resources/下。还可以上传到mongodb中。
这次使用Springboot提供了的静态资源的映射方式静态资源的映射方式
你可以添加一个外部文件夹并将其作为一个静态资源文件夹的映射,也就是说添加这个映射后你可以在项目中像访问静态资源文件夹一样来访问外部的文件夹。
具体代码:
在项目中新建一个类,创建映射的静态资源请求路径。
package com.herbert.upload.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Created by Herbert on 2020/4/8.
* zhaixingzu@163.com
*/
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("file:F:/img/");
}
}
"/img/**" 就是映射的静态资源请求路径
下来测试下静态资源是否配置成功:
在F盘符下建立文件夹img 。然后放一张图片为code.png 通过映射的静态资源请求路径访问:
启动项目
访问http://127.0.0.1:8080/img/code.png
上传文件代码:
package com.herbert.upload.controller;
import com.alibaba.fastjson.JSON;
import com.wwj.imageupload.util.FileUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;