1. 程式人生 > >springboot 上傳檔案的程式碼

springboot 上傳檔案的程式碼

後端:
@RequestMapping("/upload")
public String upload(@RequestParam(“pic”)MultipartFile file, HttpServletRequest request){
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
/System.out.println(“fileName–>” + fileName);
System.out.println(“getContentType–>” + contentType);

/
//String filePath = request.getSession().getServletContext().getRealPath(“imgupload/”);
String filePath = “D:/imgup”;
try {
this.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}

return "success";

}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}

前臺:
在這裡插入圖片描述