使用$ http.post发送formData返回较大文件的空正文

时间:2018-07-06 14:47:16

标签: javascript angularjs node.js

我正在尝试通过我的Web应用程序上传文件。我有以下代码:

查看:

<div class="row">
  <form name="rsdCtrl.viewData.uploadForm" class="form-horizontal col-sm-12">
    <div class="row voffset4">
      <div class="col-sm-4">
        <input type="file" ngf-select ng-model="rsdCtrl.viewData.file" name="file" ngf-max-size="10MB" required/>
        <i ng-show="rsdCtrl.viewData.uploadForm.file.$error.maxSize">File too large (max 10MB)</i>
      </div>
    </div>
    <div class="row voffset3">
      <div class="col-sm-4">
        <button ng-disabled="!rsdCtrl.viewData.file || rsdCtrl.viewData.uploadForm.file.$error.maxSize" class="btn btn-success" type="submit" ng-click="rsdCtrl.uploadFile()">Upload</button>
      </div>
    </div>
  </form>
</div>

控制器:

function uploadFile(){
  if (vd.uploadForm.file.$valid && vd.file) {
    $('#uploadModal').modal('show');
    return uploadService.upload(vd.file, "Convictions Calculator", "PCCS").then(function(response){
      vd.documentName = vd.file.name;
      vd.uploadedFilePath = response.data;
      $('#uploadModal').modal('hide').removeClass("in");
      $(".modal-backdrop").remove();
      alertService.setAlert('File uploaded', 'success');
    }).catch(handleServiceError);
  }
}

uploadService:

(function (){
'use strict';
angular.module('cica.common').service('uploadService', ['$http', '$window', '$routeParams', uploadService]);

function uploadService($http, $window, $routeParams) {

    this.upload = function (file, name, type) {
        const fd = new FormData();
        fd.append('document', file);
        let jobId = ($routeParams.jobId)? $routeParams.jobId: $routeParams.caseJobId;
        fd.append('jobId', jobId);
        fd.append('documentRename', name);
        fd.append('documentType', type);

        console.log(fd);
        return $http.post('/document/upload', fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).catch(function(err){
            handleHttpError('Unable to upload document.', err);
        });
    };

    function handleHttpError(prefix, response){
        throw prefix + ' HTTP Status ' + response.status + ': ' + response.statusText;

    };
  }
})();

routes.js:

    'POST /document/upload': {controller: 'DocumentController', action: 'uploadDocument'},

DocumentController:

"use strict";
const fs = require('fs');

module.exports = {
  uploadDocument: function (req, res) {
    const params = req.allParams();
    const jobId = params.jobId;
    const uploadedFileName = params.documentRename;
    const uploadedFileType = params.documentType;
    const awardsDirectoryKey = this.documentUploadDirectories.ADDITIONAL_AWARDS;
    req.file('document').upload({
        // don't allow the total upload size to exceed ~100MB
        maxBytes: 100000000
    }, function whenDone(err, uploadedFiles) {
        if (err) {
            return res.serverError(err);
        }
        // If no files were uploaded, respond with an error.
        else if (uploadedFiles.length === 0) {
            return res.serverError('No file was uploaded');
        } else {
            const filePath = uploadedFiles[0].fd;
            const filename = DocumentService.addDateToDocumentName(uploadedFiles[0].filename);
            return fs.readFile(filePath, function (err, data) {
                if (err) {
                    return res.serverError(err);
                } else {
                    const jobId = params.jobId;
                    const jobVars =
                        {
                            filePath: results.filePath,
                            fileName: uploadedFileName,
                            fileType: uploadedFileType
                        };
                    return DocumentService.uploadConvictions(req.session.sessionId, jobId, jobVars).then(function (response) {
                        return res.send("Document uploaded.");
                    }).catch(function (err) {
                        return res.serverError(err);
                    });
                }
            });
        }
    });
},

如果我上传的是带有小图片的jpeg(大约11kB),则上传的效果完全符合预期。但是,如果我尝试上传更大的jpeg(大约170kB),它就会掉下来。尽管没有立即引发/捕获的错误,但是发生的是在上载服务中创建的formData对象似乎丢失了其数据。如果我将此行插入DocumentController:

console.log(req.allParams());

结果将输出较小文件的预期变量,但对于较大文件返回空值,最终在函数尝试进一步使用这些变量时导致错误。您可以通过此方法上传的文件大小是否设置了某种限制,或者我是否配置错误?

0 个答案:

没有答案