java 後端開發–文件上傳
根據自己理解寫的備註,如有不正確處,謝謝評論指出。
public ServerResponse<?> uploadSampleFile(MultipartFile multipartFile) {
//獲取文件名稱
String originalFilename=multipartFile.getOriginalFilename();
//設置文件儲存地址
String path="/app/file/notice/files/temp/resume/";//本地也可寫成F:excel/stuInfoExcel
try {
//檢查文件夾是否存在,如果不存在則新建該文件夾
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
//獲取文件內容
FileInputStream in= (FileInputStream) multipartFile.getInputStream();
//新建輸出流文件
FileOutputStream out=new FileOutputStream(new File(path+originalFilename));
//設置文件字節,並將上傳文件內容寫入新建文件中
byte [] bytes=new byte[10240];
int len;
while((len=in.read(bytes))!=-1){
out.write(bytes, 0, len);
}
//關閉流
out.flush();
out.close();
in.close();
} catch (Exception e) {
//異常跳出
return null;
}
//正常返回文件路徑
return ServerResponse.createBySuccess(path+originalFilename);
}