【问题标题】:Post upload files in angular 4 from spring boot?从春季启动以角度4发布上传文件?
【发布时间】:2018-04-17 19:07:50
【问题描述】:

我有一个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');
  }
}
这是构建后的错误 谢谢!

【问题讨论】:

  • 您的 server 必须启用 CORS(并因此在 responses 中设置 Access-Control-Allow-Origin 标头)。阅读docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/…。或者只是从您的 Spring 引导服务器提供您的 Angular 应用程序,这将使 CORS 变得不必要。
  • 我已经在服务器和 Angular 应用程序上启用了 CORS。但是还是不行!
  • 控制台中的错误另有说明。所以要么你没有,要么你做错了。

标签: json angular rest spring-boot file-upload


【解决方案1】:

根据你分享的代码我的一些观察:

  • 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

【讨论】:

  • 我重新编码了,还是不行,让我修改一下。谢谢!
  • 我纠正了我的问题,将{'Content-Type' : 'multipart/form-data', 'Access-Control-Allow-Origin' : '*'} 替换为{'enctype' : 'multipart/form-data'}。不过,我也感谢您的帮助。
猜你喜欢
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 2015-04-18
相关资源
最近更新 更多