Java文件上傳:Restful接口接收上傳文件,緩存在本地


接口代碼

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@RestController
@RequestMapping(value = "/file")
@Slf4j
public class FileController {

    /**
     * windows下的文件路徑
     */
    private final String File_PATH = "F:/upload/temp";

    @PostMapping(value = "/upload")
    String uploadFileBufferToLocal(MultipartFile file) {

            //將文件緩沖到本地
            boolean localFile = createLocalFile(File_PATH, file);
            if(!localFile){
                log.error("Create local file failed!");
                return "Create local file failed!";
            }
            log.info("Create local file successfully");

        return "Create local file successfully";
    }

    /**
     * 通過上傳的文件名,緩沖到本地,后面才能解壓、驗證
     * @param filePath 臨時緩沖到本地的目錄
     * @param file
     */
    public boolean createLocalFile(String filePath,MultipartFile file) {
        File localFile = new File(filePath);
        //先創建目錄
        localFile.mkdirs();

        String originalFilename = file.getOriginalFilename();
        String path = filePath+"/"+originalFilename;

        log.info("createLocalFile path = {}", path);

        localFile = new File(path);
        FileOutputStream fos = null;
        InputStream in = null;
        try {

            if(localFile.exists()){
                //如果文件存在刪除文件
                boolean delete = localFile.delete();
                if (delete == false){
                    log.error("Delete exist file \"{}\" failed!!!",path,new Exception("Delete exist file \""+path+"\" failed!!!"));
                }
            }
            //創建文件
            if(!localFile.exists()){
                //如果文件不存在,則創建新的文件
                localFile.createNewFile();
                log.info("Create file successfully,the file is {}",path);
            }

            //創建文件成功后,寫入內容到文件里
            fos = new FileOutputStream(localFile);
            in = file.getInputStream();
            byte[] bytes = new byte[1024];

            int len = -1;

            while((len = in.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }

            fos.flush();
            log.info("Reading uploaded file and buffering to local successfully!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                if(fos != null) {
                    fos.close();
                }
                if(in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("InputStream or OutputStream close error : {}", e);
                return false;
            }
        }

        return true;
    }
}

過程是:

首先接口接收文件;

創建將要緩沖文件的目錄,存在指定目錄就不創建;

判斷該目錄是否有重復的文件名,如果有,先刪除再生成,如果沒有,就生成文件;

然后將通過文件流以每次1024bytes寫入指定目錄的文件;

最后關閉流。

 

更多Java文件操作可使用強大的Java文件工具:org.apache.commons.io.FileUtils;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM