zoukankan      html  css  js  c++  java
  • angularJs上传文件及表单(非form上传,cac-module)

    2019-05-22更新

    html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Bootstrap 实例 - 基本表单</title>
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
        <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
    
    </head>
    <body ng-app="myApp" ng-controller="formUploadCtrl">
    
    <form role="form">
        <div class="form-group">
            <label for="name">名称</label>
            <input type="text" class="form-control" id="name"
                   placeholder="请输入名称">
        </div>
        <div class="form-group">
            <label for="file">文件输入</label>
            <input type="file" id="file" class="file">
        </div>
        <button type="submit" class="btn btn-default" ng-click="upload()">提交</button>
    </form>
    <!--以防angularJs还未加载就加载了upload.js。就会报错,所以放到末尾-->
    <script src="upload.js"></script>
    
    </body>
    </html>

    upload.js

    var app = angular.module('myApp', []);
    app.controller('formUploadCtrl', function ($scope,$http) {
        $scope.filename = "aaa";
        $scope.upload = function(){
            console.log("=========Iam in!");
            var url = "http://localhost:8080/api/file/fileUpload";
            var user = {
    
            };
            var form = new FormData();
            var file = angular.element("#file")[0].files[0];//取文件。用angular.element("#file")一定要引入jQuery。
            form.append("fileName",file);
            form.append("user",angular.toJson(user));//toJson将json对象转成字符串,放入实体
            $http.post(url,form,{
                transformRequest: angular.identity,
                headers:{
                    'Content-Type': undefined
                }
            }).success(function (data) {
                alert("true");
            });
        }
    
    });

    java:

    //后台原本直接接收的User实体类。但是这种保护了文件及表单的时候,前端用了FormData,里面只能放字符串,放的时候讲json转为字符串。后端接收之后,将json字符串转换位实体(用的alibaba的json)
    @PostMapping("/fileUpload") public boolean fileUpload(@RequestParam("fileName") MultipartFile file, @RequestParam("user") String strUser) { if (file.isEmpty()) { return false; } //JSONObject jsonobject = JSONObject.parseObject(strUser); if (strUser != null) { User user = (User) JSON.parseObject(strUser, User.class); } String fileName = file.getOriginalFilename(); int size = (int) file.getSize(); System.out.println(fileName + "-->" + size); String path = "E:/test"; File dest = new File(path + "/" + fileName); if (!dest.getParentFile().exists()) { //判断文件父目录是否存在 dest.getParentFile().mkdir(); } try { file.transferTo(dest); //保存文件 return true; } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } }

    =======================================================================================

    angular.js:13920 Broken interceptor detected: Config object not supplied in rejection:

    <input type="file" id="file{{$index}}" class="file" ngf-select ngf-change="cacScriptUploadVm.views.changeAttach($file,$index)">
        function save() {
                console.log(vm.views.scriptList);
                var form = new FormData();
                for (var i = 0; i < vm.views.scriptList.length; i++) {
                    var file = angular.element(".file")[i].files[0];//获取文件
                    form.append("files", file);//files和后台接收字段名称一样
                }
                //传入出了file以外的实体
                /* var scriptList = JSON.stringify(vm.views.scriptList);
                form.append("script", scriptList);*/
                form.append("newDir","");//传一个字符串
                cacScriptService.uploadFile(form);           
    
    
            }
    
            function changeAttach($file, $index) {
                if ($file != null && vm.views.scriptList.length > 0 && vm.views.scriptList.length >= $index) {
                    vm.views.files[$index] = $file;
                }
            }
    function uploadFile(form) {
                var url = _appconfig.apiBaseUrls.git + '/api/git/cac/upload';
                $http({
                    method: 'POST',
                    url: url,
                    data: form,
                    headers: {'Content-Type': undefined},
                    transformRequest: angular.identity,
                    transformResponse: function(data) {  // 转换response,这样就能接收后台传回来String,默认接收是json。没写这个属性之前,上传成功后却返回到error,而且会报上面的错误,写了这个就不会
                        return data;
                    }
                }).success(function (data) {
                    console.log('upload success');
                }).error(function (data) {
                    console.log('upload fail');
                });
            }
  • 相关阅读:
    Leetcode 92. Reverse Linked List II
    Leetcode 206. Reverse Linked List
    Leetcode 763. Partition Labels
    Leetcode 746. Min Cost Climbing Stairs
    Leetcode 759. Employee Free Time
    Leetcode 763. Partition Labels
    搭建数据仓库第09篇:物理建模
    Python进阶篇:Socket多线程
    Python进阶篇:文件系统的操作
    搭建数据仓库第08篇:逻辑建模–5–维度建模核心之一致性维度2
  • 原文地址:https://www.cnblogs.com/zml-java/p/9123369.html
Copyright © 2011-2022 走看看