简体   繁体   中英

How do I upload a file using POST in angular?

How do I transmit a pdf file? I have found multiple ways online, but most of them involve a rework of how our current system works, which is far from ideal.

Im not too familiar with angular, but I am trying to upload a file to the server. i am using existing architecture, so the issue isnt as easy as simply rewriting it from the ground up. Spring complains that "The current request is not a multipart request", if i try to send it as a multipart file, but I dont know how to make it one. The file type must be of type Blob. Currently, no error is thrown, but data.content is empty after the data block is transmitted.

Here is what I currently have:

$scope.uploadPDF = function(uploadedPDF) {
    var url = 'uploadPDF';
    data = {};
    data.comments = $scope.worksheet.comments;
    data.queryId = $scope.qId;
    data.responseId = $scope.responseId;
    data.requestTS = new Date().getTime();
    data.content = uploadedPDF;
    $http.post(url, data);
};

and the function that calls it is this, it pulls in the file, generates a name and adds the name as a property to be handled serverside, does some unaffiliated logic, then calls the above function for transmission:

$scope.addPDF = function() {

 var pdfUploads = document.getElementById('file');
  if ('files' in pdfUploads)
  {
    if (pdfUploads.files.length == 0)
    {
        $scope.setReasonForChange("addPDF");
    }else
    {
        for (var i = 0; i < pdfUploads.files.length; i++)
        {
           var currentTimeZone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2];
           $scope.militaryTime = $filter('date')(Date.now(), "MM-dd-yyyy_HHmm");
           pdfUploads.files[i].generatedFileName = "QID-" + $scope.queryId + "_" + $scope.worksheet.response.PDF_DESCRIPTION + "_" + $scope.militaryTime + currentTimeZone + ".PDF";
        }
    }
} 

    var pdfComment = document.getElementById("pdfComment").value;
    if (!pdfComment)
    {
        $scope.setReasonForChange("updatePDF");

    } else
    {
        var blobPDF = new Blob([pdfUploads.files[0]], {type: 'application/pdf'});
        $scope.uploadPDF(blobPDF);
    }
}

HTML is:

<form name="UploadForm" id="UploadForm" class="details" form-on-change="formChanged()" enctype="multipart/form-data">
            <input type="file" multiple size="50" id="file" name="file" ng-disabled="is_readonly"/>
            <button ng-click="addPDF()" ng-disabled="is_readonly">Add</button>
</form>

And lastly, serverside is this, where i think data is part of a linkedhashmap, where the values are taken from in the server, and processed:

@ResponseBody
@RequestMapping(value = "/uploadPDF", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseAttachment uploadPDF(@RequestBody Data data, HttpServletRequest request) throws Exception {
    User user = (user) request.getSession(false).getAttribute(FieldConstants.USER_SESSION_ATTR);
    ResponseAttachment newPDF = responseAttachmentService.addAttachment(data, user.getUserId());

    return newPDF;

Currently, it transmits and receives the data, except the place where the file is supposed to be is empty.

I have attempted ng-fileupload, but attaching it to our product is a nightmare, especially considering that its use kinda requires the user to already know how to use angular as it has little documentation... and we have no angular people.

This question may help you.

Basically you can't send files in purely a JSON format. You have to use a multipart form and post it that way. For example:

postFile(file) {
    var postData = new FormData();
    postData.append('File', file);

    var params = {
    headers: {
        "Content-Type": undefined
    }

    $http.post(url, data, params).then([...]);
}

You'll need the extra Content-Type param so that it is sent properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM