介紹
文件上傳是后臺必不可少的技能,提供給前臺圖片上傳最為常見
今天我們來學(xué)習(xí)一下圖片上傳
開始代碼
圖片上傳比較簡單,首先們寫一個方法提供給前臺調(diào)用
創(chuàng)建公共返回類BaseResult
@Data
public class BaseResult {
private boolean success;
private String msg;
private Object data;
}
創(chuàng)建ImgsController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.tools.jstat.Token;
import zhongmeiutilsapi.td0f7.cn.base.BaseResult;
import zhongmeiutilsapi.td0f7.cn.entrty.Imgs;
import zhongmeiutilsapi.td0f7.cn.entrty.User;
import zhongmeiutilsapi.td0f7.cn.mapper.ImgsMapper;
import zhongmeiutilsapi.td0f7.cn.mapper.UserMapper;
import zhongmeiutilsapi.td0f7.cn.token.TokenUtil;
import zhongmeiutilsapi.td0f7.cn.token.UserLoginToken;
import zhongmeiutilsapi.td0f7.cn.utils.FileUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("Imgs")
public class ImgsController {
@PostMapping//文件參數(shù)必須用MultipartFile接收
public BaseResult upload(@RequestParam(value = "file") MultipartFile file) {
BaseResult data = new BaseResult();
try {
//文件保存的路徑
String path = "/www/wwwroot/app.td0f7.cn/images";
String result = FileUtils.upload(file, path, new File(file.getOriginalFilename()).getPath());
//通過工具類保存文件
data.setSuccess(true);
data.setMsg("成功上傳!");
data.setData(result);//result是保存文件后返回的路徑
} catch (Exception e) {
e.printStackTrace();
data.setMsg(e.getMessage());
//如果發(fā)生異常,則代表文件保存出錯了Success默認是false,所以不用修改
}
return data;
}
@PutMapping
public BaseResult delete(@RequestParam(value = "id") int id) {
BaseResult result = new BaseResult();
Imgs imgs = mapper.findById(id);
result.setSuccess(FileUtils.deleteFile(imgs.getPath()));
if (result.isSuccess()) mapper.delete(id);//刪除工具類返回一個bool得值,直接給Success字段
result.setMsg(result.isSuccess() ? "刪除成功!" : "刪除失敗!");//如果Success=true刪除成功,反之刪除失敗
return result;
}
}
創(chuàng)建文件上傳工具類
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;
public class FileUtils {
public static String upload(MultipartFile file, String path, String fileName) throws Exception {
// 生成新的文件名
String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
File dest = new File(realPath);
// 判斷文件父目錄是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
// 保存文件
file.transferTo(dest);
return realPath;
}
public static boolean deleteFile(String path) {
File file = new File(path);
if (file.exists()) {
return file.delete();
}
return false;
}
}
這樣圖片上傳就完成啦