简体   繁体   中英

Angular Spring Boot File Upload

I need to write an upload angular module that uses spring boot controller and multipart file. But when I am uploading the file i have an error

Current request is not a multipart request

I tried alot of changes but every time I get this error. Here is my angular file sender data service

    function uploadFile (file) {
        var deferred = $q.defer();
        var fd = new FormData();
        fd.append('file', file);

        $http({
            data : fd,
            method: 'POST',
            transformRequest: angular.identity,
            url: "/api/private/upload",
            contentType: false,
            processData: false
        }).then(function (response) {
            deferred.resolve(response.data);
        }, function (response) {
            deferred.reject(response.message);
        }).catch(function (response) {
            deferred.reject(response.message);
        });
        return deferred.promise;
    }

And here is my Controller public String singleFileUpload(@RequestParam("file") MultipartFile file) { return "redirect:/uploadStatus"; } public String singleFileUpload(@RequestParam("file") MultipartFile file) { return "redirect:/uploadStatus"; }

It is not working with or without multipart Resolver. Can you please help me with this file upload.

ArrayBuffer to blob conversion is all you need inside your uploadFile function. See a sample here

  let fileReader = new FileReader();

  fileReader.onloadend = (e) => {
    let arrayBuffer = e.target.result;
    let data = arrayBufferToBlob(arrayBuffer, file.type);

    let formData = new FormData();
    formData.append('file', data);

    // do $http request here
  };

  fileReader.readAsArrayBuffer(yourFileFromInputElement);

IN HTML

<input type="file" name="myfile" (change)="selectFile($event)" 
accept=".png" placeholder="Upload Image" required/>

IN component TS

/* File Upload request  to Upload file  */
    this.currentFileUpload = this.selectedFiles.item(0);
    let formdata: FormData = new FormData();
    formdata.append('file', this.currentFileUpload);
    this.shareServices.FileUpload(this.currentFileUpload, path, this.imageName)
      .subscribe(data => {

      })

this For Service TS

public FileUpload(editObj: File, id, getNewFileName) {
    let formdata: FormData = new FormData();
    formdata.append('file', editObj);
    return this.httpClient.post(this.Core_URL + '/submitTask/' + id + "/" + getNewFileName, formdata)


  }

This All for file Upload

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