从Spring Boot中以Angular 4的形式上传文件?

4

我有一个处理上传文件请求的api (在spring boot中)如下:

@PostMapping("/api/admin/product/{id}/upload")
public ResponseEntity<Product> postUpload(@PathVariable("id") Integer id, @RequestParam("image") MultipartFile imageFile) {
    Product product = productService.findOne(id);
    return new ResponseEntity<>(productService.upload(product, imageFile),HttpStatus.OK);
}

以下是一个处理我的请求的服务。我应该如何修复它以适应上述 API?

@Injectable()
export class ProductServiceService {
  private baseUrl = 'http://localhost:8080/api/admin/product';
  private headers = new Headers({'Content-Type' : 'multipart/form-data', 'Access-Control-Allow-Origin' : '*'});
  private options = new RequestOptions({headers: this.headers});
  constructor(private _http: Http) { }
  postUpload(id) {
    const formdata: FormData = new FormData();
formdata.append('image', image);
return this._http.post(this.baseUrl + '/' + id + '/upload', formdata, this.options)
            .map((res: Response) => res.json())
            .catch(this.errorHandler);
  }
  errorHandler(error: Response) {
    return Observable.throw(error || 'SERVER ERROR');
  }
}

And this is the error after build enter image description here Thanks!


1
你的服务器必须启用CORS(因此在响应中设置Access-Control-Allow-Origin标头)。请阅读https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/#boot-features-cors。或者,只需从Spring Boot服务器提供您的Angular应用程序,这将使CORS变得不必要。 - JB Nizet
我已经在服务器和Angular应用程序上启用了CORS。然而,它仍然无法正常工作! - Hồ Mạnh Lực
1
控制台中的错误信息表明情况并非如此。因此,要么您还没有这样做,要么您已经做错了。 - JB Nizet
1个回答

0
根据您提供的代码,我有以下几点观察:
  • private headers = new Headers({'Content-Type' : 'application/json'});。这是错误的,内容类型应该是multipart/form-data
  • this._http.get - 这应该是POST
  • 文件应该通过image请求参数关联

我不熟悉Angular,无法给您一个确切的答案。

更新:

如果您的客户端应用程序是另一个Spring Boot应用程序,则可以在Angular JS应用程序上运行Zuul代理,并将/api URL映射到http://localhost:8080/api。启用Zuul代理非常简单: * 在您的pom中添加依赖项spring-cloud-starter-zuul * 在配置类上注释@EnableZuulProxy * 在属性中添加以下内容:zuul.routes.api.url http://localhost:8080/api

所以从客户端应用程序中调用 API:http://localhost:4200/api/admin/product/17/upload,您的客户端应用程序(使用 Zuul 代理)将调用服务器上的http://localhost:8080/api/admin/product/17/upload

1
我已经重新编码了,但还是不行,让我修改一下。谢谢! - Hồ Mạnh Lực
我通过将{'Content-Type' : 'multipart/form-data', 'Access-Control-Allow-Origin' : '*'}替换为{'enctype' : 'multipart/form-data'}来解决了我的问题。不过,我也感谢你的帮助。 - Hồ Mạnh Lực

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接