实现使用PrimeVue组件实现图片上传,SpringBoot项目后台接收,存储在服务器上,返回前端图片存储地址:
前端样式:
PrimeVue标签:(url 为后台请求地址路径)
<div class="card" style="margin-top: 10px; max-width: 195px">
<Toast />
<FileUpload name="file" :url="url" @upload="onAdvancedUpload($event)":multiple="false"accept="image/*"
:maxFileSize="10000000" chooseLabel="选择" upload-label="上传" :showCancelButton="false" >
</FileUpload>
</div>
接收后台返回参数:
methods: {
async onAdvancedUpload(event) {
console.log("event.xhr.response",event.xhr.response)
let text = JSON.parse(event.xhr.response);
if ( text.code === 200){
this.hmeter.imageUrl = text.data
this.$toast.add({severity: 'success', summary: '图片上传成功!', life: 1000});
}
}
}
定义后台控制器Controller:
/**
* @Description: 上传图片的控制器
* @Author: mc 2023/5/7 05:15
*/
@RestController
@RequestMapping("/image")
public class UploadImageController {
@Autowired
private UploadImageService uploadImageService;
/**
* 上传图片路径方法
* @param file
* @return
*/
@PostMapping ( "/meter")
public ResponseVo uploadBusinessImage(@RequestParam(value = "file", required = false) MultipartFile file) {
return uploadImageService.uploadImage(file,"C:/img/meter/");
}
}
定义Service实现图片上传:
/**
* @Description: 上传图片的业务逻辑层方法
* @Author: XuWei_Yao 2023/5/7 05:16
*/
@Service
@Slf4j
public class UploadImageService {
/**
* 上传图片的业务逻辑层实现方法
*/
public ResponseVo uploadImage(MultipartFile file, String folder) {
// 上传为空返回提示
if (file == null) {
return ResponseVo.error("请选择要上传的图片!");
}
// 上传图片超过限制返回提示
if (file.getSize() > 1024 * 1024 * 10) {
return ResponseVo.error("文件大小不能大于10M!");
}
// 获取文件后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1, file.getOriginalFilename().length());
if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
return ResponseVo.error("请选择jpg,jpeg,gif,png格式的图片!");
}
String path = folder;
File savePathFile = new File(path);
if (!savePathFile.exists()) {
// 若不存在该目录,则创建目录
savePathFile.mkdir();
}
// 通过UUID生成文件名
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path + fileName));
} catch (Exception e) {
e.printStackTrace();
return ResponseVo.error("保存文件出现异常!");
}
// 向前台返回文件名
return ResponseVo.ok(path + fileName);
}
}
实现图片上传,返回上传地址: