今日份难受记录
前端
上传图片功能
目前仅实现上传图片功能[测试版]
```javascript
async uploadFile(file) {
const formData = new FormData()
console.log(file);
formData.append('image', file.raw)
try {
this.uploading = true
const response = await this.$axios.post(this.$store.state.urls.ServiceUrl+'/uploadImg', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}})
if (response.data!='') {
// 将返回的图片 URL 存储到表单数据中(假设响应包含一个 url 字段)
this.form.imageUrl = response.data.url
} else {
console.error('图片上传失败')
}
} catch (error) {
console.error('图片上传出错', error)
} finally {
this.uploading = false
}
},
后端接口实现
package com.example.meishi.Controllers;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.PathResource;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
@CrossOrigin
public class UploadImgController {
private String uploadPath;
@PostMapping("/uploadImg")
public String handleFileUpload(@RequestParam("image") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return "Please select a file to upload.";
}
// 获取图片原始名称
String fileName = file.getOriginalFilename();
ApplicationHome applicationhmoe=new ApplicationHome(this.getClass());
// 创建存放图片的完整路径
//applicationhmoe.getDir().getParentFile().getParentFile()+"\\src\\main\\resources\\static\\Images"
//applicationhmoe.getDir().getParentFile().getParentFile().getParentFile()+"\\四川省美食共享平台\\public\\img"
Path path = Paths.get(applicationhmoe.getDir().getParentFile().getParentFile().getParentFile()+"\\四川省美食共享平台\\public\\img", System.currentTimeMillis()+fileName);
System.out.println(applicationhmoe.getDir().getParentFile().getParentFile().getParentFile()+"\\四川省美食共享平台\\public\\img");
System.out.println(path);
// 将图片保存到服务器指定路径
Files.copy(file.getInputStream(), path);
// 构建图片URL
// 假设我们希望返回的是相对路径或者服务器静态资源访问路径
String imageUrl = "./img/" + fileName; // 根据实际情况调整为实际图片URL
return imageUrl;
}
}
报错
Exception processing template “/images/404.jpg”: Error resolving template [/images/404.jpg], template might not exist or might not be accessible by any of the configured Template Resolvers
这个错误信息表示Thymeleaf模板引擎在尝试解析和渲染一个名为/images/404.jpg的模板时遇到了问题。通常情况下,Thymeleaf是用来处理HTML模板文件的,而不是图片资源。
但其实我并未使用该模板,具体原因不知(java半半吊子)
但查看文件夹会发现其实图片已经上传成功
具体原因未知,查阅后再某个角落中找到一位大哥的评论
将@Controller改为RestController
改到摒除,特此记录