简体   繁体   English

将图像从Angular 7上传到Spring-boot

[英]Uploading Image from Angular 7 to Spring-boot

I am trying to make Image transfer from my Angular application to Spring boot but i seem to not be able to make it work. 我正在尝试从我的Angular应用程序进行映像传输到Spring启动,但我似乎无法使其工作。 When I am sending the POST request from angular with the file, spring boot doesn't seem to react at all,so I tested it with PostMan and I am getting the below error: 当我从文件角度发送POST请求时,弹簧启动似乎根本没有反应,所以我用PostMan测试它,我收到以下错误:

 "timestamp": "2019-05-05T06:45:26.907+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "No primary or default constructor found for class java.io.File",
    "path": "/upload"

and in Spring Boot: 并在Spring Boot中:

ERROR 18100 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for class java.io.File] with root cause

as well as Character decoding failed. 以及字符解码失败。

In the Spring output it seems to have guessed right the file type(image jpeg) and it's name. 在Spring输出中,它似乎猜对了文件类型(图像jpeg)和它的名字。

Here is Spring boot receiver: 这是Spring启动接收器:

@RequestMapping(method = RequestMethod.POST,value ="/upload")
     public void postImage(File file) throws IOException {
     System.out.println("received");
}

Later on I am planning on writing down the image in folder but for now I just want to get it. 后来我打算在文件夹中写下图像但是现在我只是想得到它。

Below is Angular part 下面是Angular部分

<form>
    <div>Title:  <input type="text" id="input" [(ngModel)]="img.name" 
[ngModelOptions]="{standalone: true}"> 
      <br>
      <input type="file" (change)='handleImages($event)' >
    </div> 
    <br>
   <button type="submit" class="confirm"(click) = 
'add()'>Confirm</button>
 </form>

component.ts: component.ts:

handleImages(Event){  
      this.selectedFile = Event.target.files[0];
      console.log(this.selectedFile);
      this.http.post('http://localhost:8080/upload',this.selectedFile)
}

You need change param File to MultipartFile 您需要将param File更改为MultipartFile

//@RequestMapping(method = RequestMethod.POST,value ="/upload")
@PostMapping(value = "/upload")
public void postImage(@RequestParam("file") MultipartFile file) throws IOException {
     System.out.println("received");
}

and wrap file content in FormData 并在FormData中包装文件内容

handleImages(Event){  
      this.selectedFile = Event.target.files[0];
      let formData = new FormData();
      formData.append("file", this.selectedFile);
      console.log(this.selectedFile);
      this.http.post('http://localhost:8080/upload',formData)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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