您好,登錄后才能下訂單哦!
使用AngularJS上傳文件
上傳文件
html
<div> <input id="fileUpload" type="file" /> <button ng-click="uploadFile()">上傳</button> </div>
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'); }) }
注意:
后臺
@RequestMapping("/upload") public void uploadFile(@RequestParam(value = "file" , required = true) MultipartFile file) { //deal with file }
注意
文件必須通過@RequestParam注解來獲取,且需指定value才能獲取到
這樣就完成了上傳文件
上傳文件的同時傳遞其他參數
html
<div> <input id="fileUpload" type="file" /> <button ng-click="ok()">上傳</button><br> <input ng-model="user.username" /> <input ng-model="user.password" /> </div>
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]
后臺
@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(); } }
注意
ObjectMapper為com.fasterxml.jackson.databind.ObjectMapper
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。