后端代码
package com.example.demo.WebController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/file")
public class UpLoadImage {
@PostMapping("/upload")
public String UpLoadImg(@RequestParam("file") MultipartFile multipartFile)
{
System.out.println("-------------开始--------------");
System.out.println(multipartFile);
System.out.println("-------------结束--------------");
String filePath="C:\\opt\\upload\\file\\imgPool\\888.jpg";
File file = new File(filePath);
try {
multipartFile.transferTo(file); //转存文件
} catch (IOException e) {
//throw new RuntimeException(e);
return "false";
}
return "success";
}
}
前端代码
<el-form-item label="文件">
<el-upload
:action="'/file/upload?dir=imgPool'"
:show-file-list="false"
:headers="uploadHeaders"
list-type="picture-card"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<el-image v-if="filePath" style="width: 100%;height: 100%" :src="fileUrl+filePath"/>
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
前端读取图片有两种方式
1、springboot做映射;
2、nginx做映射,将静态资源发布成网站
先说1:
新建一个java类
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class MyWebMvcConfig implements WebMvcConfigurer {
private String filePath = "C:/opt/upload/file/imgPool";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imgPool/**").addResourceLocations("file:" + filePath + "/");
}
}
第二种方法: