本篇文章主要講述的是關於angularjs的上傳檔案的功能,angularjs的檔案怎麼上傳你都知道嗎? angularjs是前台頁面,後台使用的是什麼你知道嗎,現在來看這篇文章吧
#使用
AngularJS
上傳檔案
Angular
頁面SpringBoot/SpirngMVC
設定為Content-Type
#上傳檔案
html
<p> <input id="fileUpload" type="file" /> <button ng-click="uploadFile()">上传</button></p>登入後複製- js
注意:
$scope.upload = function(){ var form = new FormData(); var file = document.getElementById("fileUpload").files[0]; form.append('file', file); $http({ method: 'POST', url: '/upload', data: form, headers: {'Content-Type': undefined}, transformRequest: angular.identity }).success(function (data) { console.log('upload success'); }).error(function (data) { console.log('upload fail'); }) }登入後複製- ,這樣瀏覽器不只幫我們把
'Content -Type': undefined
AngularJS預設的
'Content-Type'
是application/json
,透過設定
boundary
,如果手動設定為:
'Content-Type': multipart/form-data,後台會拋出例外:
- the request was rejected because no multipart boundary was found
,也可以不加入
html@RequestMapping("/upload") public void uploadFile(@RequestParam(value = "file" , required = true) MultipartFile file) { //deal with file }登入後複製這樣就完成了上傳檔案
- 注意
檔案必須通過@RequestParam註解來獲取,且需指定value才能取得到
#<p> <input id="fileUpload" type="file" /> <button ng-click="ok()">上传</button><br> <input ng-model="user.username" /> <input ng-model="user.password" /> </p>登入後複製
- ##js
注意
#
$scope.ok = function () { var form = new FormData(); var file = document.getElementById("fileUpload").files[0]; var user =JSON.stringify($scope.user); form.append('file', file); form.append('user',user); $http({ method: 'POST', url: '/addUser', data: form, headers: {'Content-Type': undefined}, transformRequest: angular.identity }).success(function (data) { console.log('operation success'); }).error(function (data) { console.log('operation fail'); }) };登入後複製
#需要將Object轉為String後在附加到form上,否則會直接被轉換成字串[Object,object]
###注意##############ObjectMapper###為###com .fasterxml.jackson.databind.ObjectMapper######################使用###AngularJS###上傳檔案##########本篇文章到這就結束了(想看更多就到PHP中文網###AngularJS使用手冊###中學習),有問題的可以在下方留言提問。 ############################後台(想看更多就到PHP中文網
- AngularJS開發手冊
中學習)
@RequestMapping("/upload") public Map<String, Object> upload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "user", required = true) String user) { try (FileInputStream in = (FileInputStream) headImg.getInputStream(); FileOutputStream out = new FileOutputStream("filePathAndName")) { //将Json对象解析为UserModel对象 ObjectMapper objectMapper = new ObjectMapper(); UserModel userModel = objectMapper.readValue(user, UserModel.class); //保存文件到filePathAndName int hasRead = 0; byte[] bytes = new byte[1024]; while ((hasRead = in.read(bytes)) > 0) { out.write(bytes, 0, hasRead); } } catch (IOException e) { e.printStackTrace(); } }登入後複製
以上是AngularJS怎麼上傳檔案? angularjs上傳功能的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!