【问题标题】:Sending a pdf file to a server through post request通过 post 请求将 pdf 文件发送到服务器
【发布时间】:2021-08-12 08:32:08
【问题描述】:

我的前端有一个供用户使用的 pdf 上传部分,我想从那里通过我创建的微服务将其发送到 s3 存储桶。我的微服务上有一条需要该文件的发布路线,但是当我从前端发送它时,它是空的。从前端发送文件时,我肯定遗漏了一些东西。

export class FileUpload {
   private file: File;

   constructor(
      private service: FileService;
   ) { }

   uploadFile(): void {
      const formdata = new FormData();
      formdata.append('pdf-file', this.file);

      this.service.upload(formdata).subscribe(uploaded => {
         console.log(uploaded);
      }
   }
}

export class FileService {
   constructor(private http: HttpClient) { }

   public upload(file) {
      const headers = new HttpHeaders({'Content-Type': 'multipart/form-data'});

      return this.http.post('http://myserviceurl/file', file, {headers: headers}).pipe(
         catchError(err => {
            return error;
         });  
   }
}

FileUpload类里面的file变量是用户上传的pdf文件。在我可以通过 http 请求发送之前,我有点难以弄清楚我需要对文件做什么。任何帮助将不胜感激。

【问题讨论】:

  • 你的 html 文件是什么样的?在您的上传方法中,“headers”变量是在哪里定义的?它是什么样的?

标签: angular http pdf http-post


【解决方案1】:

您的代码看起来不错。但是,我们应该了解我们对后端文件的期望。

我相信,文件或文件对象不需要任何更改。您只需要将文件作为表单数据发送。

下面是一个代码 sn-p,用于将 Angular 文件作为表单数据上传,并在 Spring Boot 中获取。

Angular sn-p(用于将文件作为表单数据上传):

uploadPdfFile(event) {
  const pdfFiles = event.target.files;
  const pdfFile = pdfFiles.item(0);

  const formdata: FormData = new FormData();
  formdata.append('pdfFile', pdfFile); // Should match the parameter name in backend

  this.http.post<any>('http://localhost:8088/file', formdata).subscribe(
  (data) => {
    console.log('Upload File ' + data);
  },
  (error) => {
    console.error(error.error);
  });
}

后端微服务(SpringBoot)用于获取参数中的文件:

@PostMapping(path = "file")
public String uploadPdfFile(@RequestParam("pdfFile") MultipartFile pdfFile) {
    // TODO: Save the file
    // TODO: Upload to S3
    return "done";
}

更多理解参考:

【讨论】:

  • 我想我明白为什么现在需要一个 FormData 对象,但即使在使用 FormData 并将我的标题更改为 'Content-Type': 'multipart/form-data' 它仍然最终作为服务接收到空对象 {}。 (我已经更新了原始代码显示以显示它现在的样子)
  • @SkinnyBetas 我建议您测试一次 API(使用 Postman)并确认后端部分是否工作正常。一旦我们确定这一点,我们就可以继续调试前端代码。
【解决方案2】:

使用FormData Angular上传文件。

//创建FormData对象

const formData = new FormData();

//在FormData中添加值

formData.Append("key","value");

然后通过将 FormData 对象作为参数传递来调用您的方法。

uploadFile(): void {
  this.service.upload(formData).subscribe(uploaded => {
     console.log(uploaded);
  }

}

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 2012-04-03
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多