在上传多个MultipartFile文件的Spring Boot中遇到错误。

huangapple go评论77阅读模式
英文:

getting error on springboot while upload list of multipartfile

问题

我正在尝试上传多个文件,在这样做时遇到了问题。请有人指出可能出了什么问题吗?

我在此附上了我代码中相关的片段,以便更好地进行调试。

**HTML代码**

    <label>
        欢迎 {{name}},欢迎来到新的应用。
    </label>
    <div>
        <input type="file" multiple placeholder="选择要上传的文件" accept=".xlsx" (change)=selectedfiles($event)>
    </div>

**上传逻辑**

    selectedfiles(event){
    
        this.selectedxlfiles=event.target.files;
    
        this.fileandinstancekeyobj.filetoupload=this.selectedxlfiles;
        this.fileandinstancekeyobj.instancekey=this.instancekey;
    
        this.uploadservice.uploadtoserver(this.fileandinstancekeyobj).subscribe(result=>{
          console.log(result);
        })
    
      }

**上传服务**

    uploadtoserver(selectedfileandinstacekeyobj): Observable<HttpEvent<{}>>{
    
         let url:string=environment.url+'uploadfile';
        const newrequest=new HttpRequest('POST',url,selectedfileandinstacekeyobj,{
          reportProgress:true,
          responseType:'text'
        });
    
        return this.http.request(newrequest);
      }

**Spring Boot控制器**

    @RestController
    public class uploadcontroller {
    
    	@PostMapping("/uploadfile")
    	public ResponseEntity<String> handleupload(@RequestBody uploaddto dto){
    		
    		System.out.println("成功");
    		System.out.println(dto.getInstancekey()+" "+dto.getFiletoupload().length);
    		
    		
    		return ResponseEntity.status(HttpStatus.OK).body("ok");
    	}

**上传DTO**
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    
    import org.springframework.web.multipart.MultipartFile;
    
    class uploaddto {
    	
    	List<MultipartFile> filetoupload;
    	String instancekey;
    	public uploaddto(List<MultipartFile> filetoupload, String instancekey) {
    		super();
    		filetoupload=new ArrayList<MultipartFile>();
    		this.filetoupload = filetoupload;
    		this.instancekey = instancekey;
    	}
    	public List<MultipartFile> getFiletoupload() {
    		return filetoupload;
    	}
    	public void setFiletoupload(List<MultipartFile> filetoupload) {
    		this.filetoupload = filetoupload;
    	}
    	public String getInstancekey() {
    		return instancekey;
    	}
    	public void setInstancekey(String instancekey) {
    		this.instancekey = instancekey;
    	}
    	
    	
    }
我收到以下错误消息

    [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: 
    Cannot deserialize instance of `java.util.ArrayList<org.springframework.web.multipart.MultipartFile>` out of START_OBJECT token; 
    nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
    Cannot deserialize instance of `java.util.ArrayList<org.springframework.web.multipart.MultipartFile>` out of START_OBJECT token
         at [Source: (PushbackInputStream); line: 1, column: 17] (through reference chain: com.example.demo.uploaddto["filetoupload"])]

**欢迎任何建议**
英文:

I am trying to upload multiple files and I am facing an issue while doing so. Can someone please suggest what is wrong?

I am enclosing relevant snippets of my code to debug better.

html code

&lt;label&gt;
    welcome {{name}}, welcome to new app.
&lt;/label&gt;
&lt;div&gt;
    &lt;input type=&quot;file&quot; multiple placeholder=&quot;Select Files to be upload&quot; accept=&quot;.xlsx&quot; (change)=selectedfiles($event)&gt;
&lt;/div&gt;

upload logic

selectedfiles(event){

    this.selectedxlfiles=event.target.files;

    this.fileandinstancekeyobj.filetoupload=this.selectedxlfiles;
    this.fileandinstancekeyobj.instancekey=this.instancekey;

    this.uploadservice.uploadtoserver(this.fileandinstancekeyobj).subscribe(result=&gt;{
      console.log(result);
    })

  }

uploadservice

uploadtoserver(selectedfileandinstacekeyobj): Observable&lt;HttpEvent&lt;{}&gt;&gt;{

     let url:string=environment.url+&#39;uploadfile&#39;;
    const newrequest=new HttpRequest(&#39;POST&#39;,url,selectedfileandinstacekeyobj,{
      reportProgress:true,
      responseType:&#39;text&#39;
    });

    return this.http.request(newrequest);
  }

springboot controller

@RestController
public class uploadcontroller {

	@PostMapping(&quot;/uploadfile&quot;)
	public ResponseEntity&lt;String&gt; handleupload(@RequestBody uploaddto dto){
		
		System.out.println(&quot;sucessfull&quot;);
		System.out.println(dto.getInstancekey()+&quot; &quot;+dto.getFiletoupload().length);
		
		
		return ResponseEntity.status(HttpStatus.OK).body(&quot;ok&quot;);
	}

upload DTO

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

class uploaddto {
	
	List&lt;MultipartFile&gt; filetoupload;
	String instancekey;
	public uploaddto(List&lt;MultipartFile&gt; filetoupload, String instancekey) {
		super();
		filetoupload=new ArrayList&lt;MultipartFile&gt;();
		this.filetoupload = filetoupload;
		this.instancekey = instancekey;
	}
	public List&lt;MultipartFile&gt; getFiletoupload() {
		return filetoupload;
	}
	public void setFiletoupload(List&lt;MultipartFile&gt; filetoupload) {
		this.filetoupload = filetoupload;
	}
	public String getInstancekey() {
		return instancekey;
	}
	public void setInstancekey(String instancekey) {
		this.instancekey = instancekey;
	}
	
	
}

I am receiving the following error

[org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: 
Cannot deserialize instance of `java.util.ArrayList&lt;org.springframework.web.multipart.MultipartFile&gt;` out of START_OBJECT token; 
nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize instance of `java.util.ArrayList&lt;org.springframework.web.multipart.MultipartFile&gt;` out of START_OBJECT token
     at [Source: (PushbackInputStream); line: 1, column: 17] (through reference chain: com.example.demo.uploaddto[&quot;filetoupload&quot;])]

Any suggestion would be appreciated

答案1

得分: 1

以下是您要翻译的内容:

我正在添加这个答案,以便我可以帮助某人挽救他的一天,我所做的更改如下:

在 UploadController 中的更改

this.selectedxlfiles = event.target.files;
const data: FormData = new FormData();
for (let i = 0; i < this.selectedxlfiles.length; i++) {
  this.currentfile = this.selectedxlfiles[i];
  data.append('selectedfile', this.currentfile);
}
data.append('instancekey', this.instancekey);
this.uploadservice.uploadtoserver(data).subscribe(Response => {
  console.log(Response);
})

在 UploadService 中的更改

uploadtoserver(data: FormData): Observable<HttpEvent<{}>> {

  let url: string = environment.url + 'uploadfile';
  const newrequest = new HttpRequest('POST', url, data, {
    reportProgress: true,
    responseType: 'text',
  });

  return this.http.request(newrequest);
}

在 Spring Boot 控制器中的更改

@RestController
public class UploadController {

  @PostMapping("/uploadfile")
  public ResponseEntity<String> handleUpload(@ModelAttribute UploadDto dto) {

    System.out.println("成功");
    System.out.println(dto.getInstanceKey() + " " + dto.getFileToUpload().length);

    return ResponseEntity.status(HttpStatus.OK).body("ok");
  }
}

控制器中唯一的更改是 @ModelAttribute

英文:

I am adding this answer so that i could help someone save his day, what i did

change in uploadcontroller

this.selectedxlfiles=event.target.files;
  const data:FormData=new FormData();
for(let i=0;i&lt;this.selectedxlfiles.length;i++){
  this.currentfile=this.selectedxlfiles[i];
  data.append(&#39;selectedfile&#39;,this.currentfile);
}
data.append(&#39;instancekey&#39;,this.instancekey);
this.uploadservice.uploadtoserver(data).subscribe(Response=&gt;{
  console.log(Response);
})

changes in upload service

uploadtoserver(data:FormData): Observable&lt;HttpEvent&lt;{}&gt;&gt;{

      let url:string=environment.url+&#39;uploadfile&#39;;
    // console.log(url);
    //  const data: FormData=new FormData();
    //  data.append(&#39;selectedfile&#39;,selectedfile);
    //  data.append(&#39;instancekey&#39;,instancekey);
    const newrequest=new HttpRequest(&#39;POST&#39;,url,data,{
      reportProgress: true,
      responseType: &#39;text&#39;,
    });
    

    return this.http.request(newrequest);
    //return this.http.post(url,selectedfiles);
  }

changes in springboot controller

@RestController
public class uploadcontroller {

    @PostMapping(&quot;/uploadfile&quot;)
    public ResponseEntity&lt;String&gt; handleupload(@ModelAttribute uploaddto dto){
        
        System.out.println(&quot;sucessfull&quot;);
        System.out.println(dto.getInstancekey()+&quot; &quot;+dto.getFiletoupload().length);
        
        
        return ResponseEntity.status(HttpStatus.OK).body(&quot;ok&quot;);
    }

the only change in controller @modelattribute

huangapple
  • 本文由 发表于 2020年9月21日 15:34:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63987945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定