1. 程式人生 > >Java檔案上傳:Restful介面接收上傳檔案,快取在本地

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寫入指定目錄的檔案;

最後關閉流。