Alex2330
Alex2330

Reputation: 347

Spring MultipartException: The current request is not a multipart request

I'm trying to upload a file with AngularJS and Spring controller. The Angular controller looks like this:

 $scope.uploadFile=function(){
 var formData=new FormData();
 formData.append("file",file.files[0]);

 $http.post('/content-files/upload /',  file.files[0], {

     transformRequest: function(data, headersGetterFunction) {
            return data; // do nothing! FormData is very good!
        },
     headers: {'Content-Type': undefined }

 })
 .success(function(){
     console.log('Post Succeded !');
 })
 .error(function(){
     console.log('Post Failed .');
 });
}

I also try this:

var formData = new FormData();
formData.append('file',file.files[0]);

$http.post('/content-files/upload /',  formData, {         
  headers: { 'Content-Type': undefined },
  transformRequest: angular.identity
})

and the Spring controller looks like this:

    @RequestMapping(value = "/content-files/upload/", method =   RequestMethod.POST  )           
public @ResponseBody String handleFileUpload(  @RequestParam("file")      MultipartFile file) {
  System.out.println("BrandController.uploadMultipart()");

String name=file.getName();
if (!file.isEmpty()) {
    try {
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream =
                      new BufferedOutputStream(new FileOutputStream(new File(name)));
        stream.write(bytes);
        stream.close();
        return "You successfully uploaded " + name + "!";
    } catch (Exception e) {
        return "You failed to upload " + name + " => " + e.getMessage();
    }
} else {
    return "You failed to upload " + name + " because the file was empty.";
 }
 }

My html Page is :

 <form enctype="multipart/form-data">
   <input id="file-0a" class="file" type="file" file-model="myFile" name="myFile" />
                 <button ng-click="uploadFile()">upload me</button></form>

i have 2 jars in web-inf/lib:commons-upload.jar and commons-io.jar I add this in my spring configuration file:

<bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="50000000"/>
</bean> 

When I'm trying to upload a file, I get the error:

   org.springframework.web.multipart.MultipartException: The current request is   not a multipart request

When I'm trying to upload a file using MultipartHttpServletRequest in my spring function instead of Multipart i get this error:

    java.lang.IllegalStateException: Current request is not of type   [org.springframework.web.multipart.MultipartHttpServletRequest]: org.apache.catalina.connector.RequestFacade@196f5636

When i use HttpServletRequest request and i try to cast it i got a ClassCastException. Nothing change when i cancel enctype="multipart/form-data" from my form Tag

Upvotes: 2

Views: 6195

Answers (2)

Saqy G
Saqy G

Reputation: 806

I stuck into the same problem. Below is angular code

things you should do:

  1. Remove the Content-Type from headers.
  2. For multi file upload use below code
handleImageUpload = async (event) => {
    if (event.target.files && event.target.files) {
      const files = event.target.files;
      _.map(files, (file) => {
        //array for multiple files upload
        this.imageData.push(file);
        const reader = new FileReader();
        //base64 encoded image for preview
        reader.onload = async (event: any) => {
          this.album.push(event.target.result);
        };
        reader.readAsDataURL(file);
      });
      this.uploadedImage = Promise.resolve(this.album);
    }
  }

In you submit handler use this code

const formData: any = new FormData();
 // adding multiple files
    this.imageData.map((i) => {
      formData.append("files", i);
    });
    // add objects
    _.map(body,(value,key) => {
      formData.append(key, value);
    });
    // delete headers it will be set by browser
    headers = headers.delete("Content-Type");
    // make a call to api
    this.httpClient
      .post(url, formData, { headers })
      .subscribe((res) => console.log(res));

Upvotes: 0

gangdaner
gangdaner

Reputation: 61

Two things needed: 1. headers: {'Content-Type': 'application/x-www-form-urlencoded'} 2. The data passed should be converted to a URL-encoded string reference: enter link description here

Upvotes: 2

Related Questions