您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。