springBoot+jpa實現圖片上傳功能

springBoot+jpa實現圖片上傳功能

擴展知識點

  1. spring集成了MultipartFile接口,該接口爲參數https://blog.csdn.net/woainike/article/details/6620862
  2. 有一個實現類,CommonsMultipartFile,該實現類用於==讀取文件== 的類,至關於讀取流,將本地文件讀入內存,這是inputStream輸入流的封裝。由於MultipartFile接口繼承了InputStream。能夠經過看源碼知道了解。
  3. java中的正斜槓‘/’和反斜槓‘\’問題:https://blog.csdn.net/qq_33393542/article/details/80336945

圖片上傳功能的實現步驟

  1. 首先判斷讀取的文件是否爲空
if (file.isEmpty()) {
    System.out.println("文件爲空空");
}
  1. 獲取文件名
String fileName = file.getOriginalFilename();  // 文件名
  1. 獲取文件名後綴
String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 後綴名
  1. 由於要限制上傳文件的類型,因此要判斷文件名後綴是否屬於要求的類型
if(!suffixName.equals(".jpg") && !suffixName.equals(".png")){
    return Result.error("請選擇圖片!!!");
}
  1. 文件上傳到服務器的文件存儲路徑
String filePath = "D://temp-rainy//"; // 上傳後的路徑
  1. 爲了防止文件重名,添加uuid前綴
fileName = UUID.randomUUID() + suffixName; // 新文件名
  1. 建立上傳到服務器的文件的路徑
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
    dest.getParentFile().mkdirs();
}
  1. 上傳文件到服務器,至關於將內存的文件輸出到服務器,OutputStream,須要try....catch....
try {
    file.transferTo(dest);
} catch (IOException e) {
    e.printStackTrace();
}
  1. 將文件路徑返回給前端,讓前端進行下載或者查看圖片。
String filename = "/temp-rainy/" + fileName;
return Result.success(filename);

源碼

@RestController
@RequestMapping(value = "/baseTest")
@CrossOrigin(origins = {"*","null"})
public class BaseTestController {
    @PostMapping(value = "/base64Upload")
    public Result uploadImage(@RequestParam(value = "file") MultipartFile file,  HttpServletRequest request, HttpServletResponse response) throws Exception{
        if (file.isEmpty()) {
            System.out.println("文件爲空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 後綴名
        if(!suffixName.equals(".jpg") && !suffixName.equals(".png")){
            return Result.error("請選擇圖片!!!");
        }
        String filePath = "D://temp-rainy//"; // 上傳後的路徑
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/temp-rainy/" + fileName;
        return Result.success(filename);
    }
}

參考文章:html

  1. https://blog.csdn.net/u013380777/article/details/58603803
  2. https://blog.csdn.net/qq_41441312/article/details/80287498
  3. https://blog.csdn.net/ZHOU_VIP/article/details/88242482
  4. https://www.cnblogs.com/jueyushanlang/p/9243647.html
  5. https://blog.csdn.net/woainike/article/details/6620862
  6. https://blog.csdn.net/zerolaw/article/details/81083018
  7. https://blog.csdn.net/Peter_S/article/details/84951978
  8. https://blog.csdn.net/sdut406/article/details/85647982
相關文章
相關標籤/搜索