使用AngularJS上傳文件
在嶧城等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作按需定制設(shè)計(jì),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計(jì),全網(wǎng)整合營(yíng)銷(xiāo)推廣,外貿(mào)網(wǎng)站制作,嶧城網(wǎng)站建設(shè)費(fèi)用合理。
上傳文件
html
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'); }) }
注意:
后臺(tái)
@RequestMapping("/upload") public void uploadFile(@RequestParam(value = "file" , required = true) MultipartFile file) { //deal with file }
注意
文件必須通過(guò)@RequestParam注解來(lái)獲取,且需指定value才能獲取到
這樣就完成了上傳文件
上傳文件的同時(shí)傳遞其他參數(shù)
html
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轉(zhuǎn)為String后在附加到form上,否則會(huì)直接被轉(zhuǎn)為字符串[Object,object]
后臺(tái)
@RequestMapping("/upload") public Mapupload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "user", required = true) String user) { try (FileInputStream in = (FileInputStream) headImg.getInputStream(); FileOutputStream out = new FileOutputStream("filePathAndName")) { //將Json對(duì)象解析為UserModel對(duì)象 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。