前端用的vue-element-ui,后端springboot,图片上传到本地的指定路径下,如:/usr/downloads/**
上传代码比较简单
@Override
public String upload(HttpServletRequest request) {
String fileName = "";
try {
Collection<Part> parts = request.getParts();
for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext(); ) {
Part part = iterator.next();
InputStream inputStream = part.getInputStream();
String suffix = FileUtil.extName(part.getSubmittedFileName());
fileName = RandomUtil.randomString(20) + "." + suffix;
File dir = new File(this.path);
if (!dir.exists()) {
dir.mkdirs();
}
path = this.path + fileName;
IoUtil.copy(inputStream, new FileOutputStream(path), IoUtil.DEFAULT_BUFFER_SIZE);
}
} catch (Exception e) {
throw new RRException("上传失败");
}
return fileName;
}
在上传成功后,返回附件的新文件名,放到fileList中,用于el-upload回显
<el-upload
:action="url"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:limit="1"
:headers="headers"
:file-list="filesList"
>
<i class="el-icon-plus"></i>
</el-upload>
如果url直接=新文件名或者文件的绝对路径,打开控制台,就会有404错误,它会在路径前面加上服务器地址,如下
http://localhost:8014//usr/downloads/**
这个时候就需要在后端做图片的静态映射,springboot如下,
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Windows下
// registry.addResourceHandler("/uploads2/**").addResourceLocations("file:D:/uploads2/");
//Mac或Linux下(没有CDEF盘符)
registry.addResourceHandler("/fileCall/**").addResourceLocations("file:/usr/downloads/");
}
}
在修改前端图片的访问路径如下,
this.filesList.push({
url: "/proxyApi/fileCall/" + data.tripCode.path,
});
访问后台的时候就会映射到图片的实际路径下
http://localhost:8014/proxyApi/fileCall/pkit7zt792n9r2gcpve6.png
就可以获取到图片啦。