1. 程式人生 > >SpringBoot輕鬆實現檔案上傳

SpringBoot輕鬆實現檔案上傳

題記:
上傳檔案在我們的功能中十分常見,剛開始接觸的程式設計師,可能覺得java上傳檔案怎麼比php這麼複雜,的確,PHP上傳檔案可以簡單到就一句話並且不需要我們自己載入函式啊,包啊,類啊什麼的,而java可以複雜到,寫一頁的程式碼可能還完不成上傳功能,當然,那是IO流的方式,屬於java基礎範疇,今天我們採用SpringBoot來實現檔案的上傳功能,也可以簡單到只寫一句話哦!

下面是檔案上傳程式碼示例:
1、工具:IDEA

2、建立SpringBoot的web應用

即在建立的時候,只勾選web

(or

3、假如你在第二步建立的時候,什麼也沒做,一路Next,那麼你只需要你的pom.xml

檔案中的dependencies有下面這些內容

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId
>
spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>

)

4、下面就是上傳程式碼了

    public void uploadFile( MultipartFile file) {

        try {

            String parentFile = "E:\\Workspace\\Temp\\file\\";

            File in = new File(parentFile + file.getOriginalFilename());

            File dest = in
.getParentFile(); if (!dest.exists()) //如果這個檔案不存在 { dest.mkdirs(); //建立 } file.transferTo(in); // copy boolean isFileDelete = in.delete(); // delete file if (!isFileDelete) //刪除失敗 { System.out.println("刪除失敗"); } } catch (IOException e) { e.printStackTrace(); } }

5、呼叫示例

    @RequestMapping(value = "/test")
    public String test(@RequestParam(value = "file") MultipartFile file) {

        uploadFile(file);

    }

後記:

上傳檔案就這麼簡單?