SpringBoot結合angularjs表單上傳檔案
阿新 • • 發佈:2019-01-10
前端程式碼:
<form id="form_upload">
<input id="upload_img_id" type="file" name="fileName"/>
<button ng-click="uploadFile()" type="button">
上傳
</button>
</form>
angularjs程式碼
this.uploadFile = function(){
//重點1:form_upload是form表單的id
var formData = new FormData(document.getElementById("form_upload"));
//重點2:upload_img_id是檔案input的id
var file = document.getElementById("upload_img_id").files[0];
//重點3:向formData中新增資料:
formData.append("file",file);
//下面是angularjs的程式碼,可以換成其他前端程式碼實現,重點是formData上傳
return $http({
method:'post',
url:'/seller/fileload/uploadFile.do',
data:formData,
headers:{'Content-Type':undefined} ,// Content-Type : text/html text/plain
transformRequest:angular.identity
//瀏覽器會幫我們把Content-Type 設定為 multipart/form-data.
});
}
端java程式碼(SpringBoot的),SpringBoot自帶檔案上傳,可以直接用
//重點4:@RequestParam("fileName")這個跟前端的input標籤的name一致
@RequestMapping(value = "uploadFile.do", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file){
System.out.println(file.getOriginalFilename()+">>>>>>>>>");
if(file.isEmpty()){
return "false";
}
String fileName = file.getOriginalFilename();//z.png
int size = (int) file.getSize();
//fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
String path = System.getProperty("user.dir");// /Users/apple/Desktop/IDEAWORKSPACE/day2/shoppingmall2
File dest = new File(path+"/target/classes/static/img" + "/" + fileName);
if(!dest.getParentFile().exists()){ //判斷檔案父目錄是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); //儲存檔案
return "{\"img_path\":\"http://localhost:8080/img/"+fileName+"\"}";
} catch (IllegalStateException e) {
e.printStackTrace();
return "false";
} catch (IOException e) {
e.printStackTrace();
return "false";
}
}