angularjs php上传文件,AngularJS怎么上传文件?angularjs上传功能的详细介绍

本篇文章主要讲述的是关于angularjs的上传文件的功能,angularjs的文件怎么上传你都知道吗?angularjs是前台页面,后台使用的是什么你知道吗,现在来看这篇文章吧使用AngularJS上传文件前台是Angular页面

后台使用SpringBoot/SpirngMVC

上传文件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');

})

}注意:AngularJS默认的'Content-Type'是application/json ,通过设置'Content-Type': undefined,这样浏览器不仅帮我们把Content-Type 设置为 multipart/form-data,还填充上当前的boundary,

如果手动设置为:'Content-Type': multipart/form-data,后台会抛出异常:the request was rejected because no multipart boundary was found

boundary 是随机生成的字符串,用来分隔文本的开始和结束

通过设置 transformRequest: angular.identity ,anjularjs transformRequest function 将序列化我们的formdata object,也可以不添加后台@RequestMapping("/upload") public void uploadFile(@RequestParam(value = "file" , required = true) MultipartFile file) { //deal with file

}注意文件必须通过@RequestParam注解来获取,且需指定value才能获取到这样就完成了上传文件

上传文件的同时传递其他参数html

上传

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]后台(想看更多就到PHP中文网AngularJS开发手册中学习)@RequestMapping("/upload") public Map 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使用AngularJS上传文件

本篇文章到这就结束了(想看更多就到PHP中文网AngularJS使用手册中学习),有问题的可以在下方留言提问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值