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');
            });
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM