首页 > web前端 > js教程 > 正文

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

寻∝梦
发布: 2018-09-08 15:00:53
原创
3689人浏览过

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

使用AngularJS上传文件
  • 前台是angular页面

  • 后台使用SpringBoot/SpirngMVC


上传文件

  • 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');
            })
        }
登录后复制

注意:

  • 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

    <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]

    @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

使用AngularJS上传文件

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

以上就是AngularJS怎么上传文件?angularjs上传功能的详细介绍的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号