public class FileUtil {
public static void uploadFile(byte[] file,String filePath,String fileName) throws IOException {
File targetFile = new File(filePath);
if (!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(targetFile.getAbsolutePath() + "/" + fileName);
out.write(file);
out.flush();
out.close();
}
public static String getUpLoadFilePath(){
File path = null;
try {
path=new File(ResourceUtils.getURL("classpath:").getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (!path.exists()) path =new File("");
File filePath=new File(path.getAbsolutePath(),"static/images/upload/");
return filePath.getAbsolutePath();
}
}
上面是fileUtil包用来实现图片下载
前端代码如下
<el-form-item label="图片上传">
<el-upload
class="avatar-uploader"
action="http://localhost:8080/file/upload"
:show-file-list="false"
:on-success="handleSuccess"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" alt="asd"/>
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
</el-form-item>
前端数据定义
imageUrl:"",//图片地址
组件注册和成功方法
components:{
Plus
},
methods: {
handleSuccess(res){
console.log(res)
console.log(res.data)
this.imageUrl="http://localhost:8080/images/upload/"+res.data
},
后端允许静态访问
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
controller方法
public class UploadController {
@Resource
UploadService uploadService;
@PostMapping("/upload")
Result<String> uploadImage(MultipartFile file){
String oldFilename = file.getOriginalFilename();
String filePath = FileUtil.getUpLoadFilePath();
String newFilename = System.currentTimeMillis() + oldFilename;
try {
FileUtil.uploadFile(file.getBytes(),filePath,newFilename);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new Result<>(State.SUCCESS,newFilename);
}
}