NIO單文件上傳

用到的依賴(這些不是必須的,只是爲了方便調試使用)

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
package com.xx.demo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@Slf4j
@Api(value = "測試文件上傳")
public class Test {

    final String path = "G:\\images\\";

    @PostMapping("/oneFileUpload")
    @ApiOperation(value = "測試單文件上傳接口")
    public String oneFileUpload (MultipartFile file, String username, String password) throws IOException {

        log.info(username + "," + password);

        // 判斷文件是否爲空
        if(file == null){
            log.info("文件不能爲空");
            return "文件不能爲空";
        }else{
            // 獲取文件名
            String fileName = file.getOriginalFilename();
            // 獲取文件後綴名
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 獲取文件類型,校驗文件的合法性
            String contentType = file.getContentType();
            if(contentType.contains("image")){
                log.info("上傳的文件是圖片");
                // 設置文件存儲路徑,使用新的文件名,避免文件名衝突
                String finalPath = this.path + System.currentTimeMillis() + "." + suffixName;
                Path path = Paths.get(finalPath);
                Files.write(path, file.getBytes());
                return "文件上傳成功";
            }else{
                log.info("上傳的文件不是圖片");
                return "文件類型不是圖片";
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章