图片文件的上传与返回
在最初的两个实现类中,其中一个,就是banner,banner中存储了对应的横幅图,但是所谓的insert与update,实际上仅仅只是内容参数的传递,并不是实际的文件,因此,在这里进行第一个功能的实现,图片上传
上传本地
1. 导入
import java.io.File;
import org.springframework.web.multipart.MultipartFile;
创建图片文件夹uploads
2.修改代码
@ApiOperation(value = "Add a new banner", notes = "Add a new banner to the system")
@PostMapping("/upload")
public Result<String> insertBanner(@ApiParam(value = "File to be uploaded", required = true) @RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return Result.error(ResultCode.ERROR, "File is empty");
}
try {
// 文件保存路径
String uploadDir = "D:\\a_awork\\springtest\\uploads"; // 请替换为实际的本地路径
String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
File dest = new File(uploadDir, fileName);
// 保存文件
file.transferTo(dest);
// 生成文件的URL或路径
String fileUrl = "/uploads/" + fileName;
// 保存文件路径到数据库
Banner banner = new Banner();
banner.setPic(fileUrl);
int result = bannerService.insertBanner(banner);
return result > 0 ? Result.success("Banner added", fileUrl) : Result.error(ResultCode.ERROR, "Failed to add banner");
} catch (IOException e) {
return Result.error(ResultCode.ERROR, "File upload failed: " + e.getMessage());
}
}
@ApiOperation(value = "Update an existing banner", notes = "Update an existing banner by its ID")
@PutMapping("/upload/{id}")
public Result<String> updateBanner(@ApiParam(value = "ID of the banner to update", required = true) @PathVariable int id,
@ApiParam(value = "Updated banner file", required = true) @RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return Result.error(ResultCode.ERROR, "File is empty");
}
try {
// 文件保存路径
String uploadDir = "D:\\a_awork\\springtest\\uploads"; // 请替换为实际的本地路径
String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
File dest = new File(uploadDir, fileName);
// 保存文件
file.transferTo(dest);
// 生成文件的URL或路径
String fileUrl = "/uploads/" + fileName;
// 更新数据库中的文件路径
Banner banner = new Banner();
banner.setId(id);
banner.setPic(fileUrl);
int result = bannerService.updateBanner(banner);
return result > 0 ? Result.success("Banner updated", fileUrl) : Result.error(ResultCode.ERROR, "Failed to update banner");
} catch (IOException e) {
return Result.error(ResultCode.ERROR, "File update failed: " + e.getMessage());
}
}
测试
使用knife4j似乎上传文件并不方便,这里选用apipost进行测试
每一次的update等操作,就会对应的在这里存储对应的对象
图片获取
这里返回了对应的相对地址值,需要前端对相对路径进行引用。这样来进行显示