File Upload using AngularJS

前端 未结 29 2034
野趣味
野趣味 2020-11-21 07:24

Here is my HTML form:

29条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 08:03

    I am able to upload files using AngularJS by using below code:

    The file for the argument that needs to be passed for the function ngUploadFileUpload is $scope.file as per your question.

    The key point here is to use transformRequest: []. This will prevent $http with messing with the contents of the file.

           function getFileBuffer(file) {
                var deferred = new $q.defer();
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    deferred.resolve(e.target.result);
                }
                reader.onerror = function (e) {
                    deferred.reject(e.target.error);
                }
    
                reader.readAsArrayBuffer(file);
                return deferred.promise;
            }
    
            function ngUploadFileUpload(endPointUrl, file) {
    
                var deferred = new $q.defer();
                getFileBuffer(file).then(function (arrayBuffer) {
    
                    $http({
                        method: 'POST',
                        url: endPointUrl,
                        headers: {
                            "accept": "application/json;odata=verbose",
                            'X-RequestDigest': spContext.securityValidation,
                            "content-length": arrayBuffer.byteLength
                        },
                        data: arrayBuffer,
                        transformRequest: []
                    }).then(function (data) {
                        deferred.resolve(data);
                    }, function (error) {
                        deferred.reject(error);
                        console.error("Error", error)
                    });
                }, function (error) {
                    console.error("Error", error)
                });
    
                return deferred.promise;
    
            }
    

提交回复
热议问题