App下載

Springboot項目中自定義工具類來實現(xiàn)后臺上傳圖片的操作

酷酷的小傻子 2021-08-09 15:48:10 瀏覽數(shù) (2191)
反饋

本篇文章將和大家分享在Springboot中自定義一個工具類,用在后臺上傳圖片的操作,以下是詳細(xì)內(nèi)容和實例代碼,供大家學(xué)習(xí)參考,希望能夠幫助大家的學(xué)習(xí)!

1.先配置啟動類

繼承WebMvcConfigurer

重寫方法

@SpringBootApplication
//@MapperScan("com.example.demo.Mapper")
public class DemoApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        /*
            addResoureHandler:指的是對外暴露的訪問路徑
            addResourceLocations:指的是內(nèi)部文件放置的目錄
        */
        registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/image");
    }
}

2.添加一個UploadUtil文件上傳工具類

public class UploadUtil {
    //源文件名
    private String originalFilename;

    //源文件后綴名
    private String suffix;

    //存入數(shù)據(jù)庫里的tomcat虛擬路徑
    private String dbPath;

    //文件大小
    private long size;

    //實際存儲路徑
    private String realPath;

    /**
     * 文件上傳工具類
     * @param attach
     * @param request
     * @param uploader 文件上傳者
     * @return
     */
    public boolean doUpload(MultipartFile attach, HttpServletRequest request, String uploader){

        if(!attach.isEmpty()){
            originalFilename = attach.getOriginalFilename();
            System.out.println("==>上傳的文件名:"+originalFilename);

            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println("==>上傳的文件后綴名:"+suffix);

            size = attach.getSize();
            System.out.println("==>上傳文件的大?。?+size);

            String currentFilename = System.currentTimeMillis()+ UUID.randomUUID().toString() + suffix;
            System.out.println("==>存儲的上傳文件名:"+currentFilename);

            realPath = "D:/image/"+uploader ;
            System.out.println("==>上傳文件保存的真實路徑:"+realPath);

            File targetFile = new File(realPath, currentFilename);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }

            try{
                attach.transferTo(targetFile);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            realPath = realPath + "/" + currentFilename;
//            dbPath =  request.getContextPath() + "/" + uploader + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + currentFilename;
            dbPath = "/" + uploader + "/" + currentFilename;
            return true;
        }else{
            return false;
        }
    }
    public String getUploadFile(){
        return dbPath;
    }
}

其中關(guān)于路徑都需要改成自己存放圖片的路徑

3.Controller層

@RestController
public class UserPhotoController {

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public String testUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        UploadUtil uploadUtil = new UploadUtil();
        String fileName = "";
        if (uploadUtil.doUpload(file, request, "uploadImg")) {
            fileName = uploadUtil.getUploadFile();
        } else {
            fileName = "file";
        }

        return fileName;
    }
}

完成。
附上RunApi接口測試工具測試過程(測試工具大同小異都是差不多步驟(如postman))

2021420112453584

Headers:

注意這里的Headers部分不要寫任何東西。
如果之前是有Content-Type頭信息, 那么就會上傳失敗.

參數(shù)選擇form-data

key:后臺規(guī)定的接收文件的名稱參數(shù)(切記不是你傳的圖片名稱)
(比如我是file)

key的格式選擇為File

value:自動變成 選擇文件

點擊發(fā)送

可以發(fā)現(xiàn)-上傳圖片成功(存到了你設(shè)置的路徑中自動創(chuàng)建upload文件夾)
控制臺也輸出了你上傳的圖片信息

2021420112509968

ok
大功告成

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持W3Cschool。如果大家對于Springboot項目的相關(guān)內(nèi)容感興趣,可以在官網(wǎng)搜索相關(guān)的技術(shù)文章。

0 人點贊