将 PDF 文件从 Angular 上传到 Spring Boot 时遇到问题

问题描述 投票:0回答:1

我对 Spring Boot 和 Angular 比较陌生,在从前端上传 PDF 文件到后端时遇到困难。

Spring Boot 服务:

@Service
public class BankStatementService{


    public BankStatement uploadFile(MultipartFile file) {
        BankStatement bankStatement = new BankStatement();
        String fileName = file.getOriginalFilename();
        String fileType = file.getContentType();
        ServletUriComponentsBuilder downloadURl = ServletUriComponentsBuilder.fromCurrentContextPath();
        long data = file.getSize();
        if (StringUtils.isEmpty(fileName)) {
            fileName = file.getName();

        }
        bankStatement.setFileName(fileName);
        bankStatement.setFileType(fileType);
        bankStatement.setData(data);
        bankStatement.setDownloadURl(downloadURl);
        return bankStatement;
    }

Spring Boot 控制器:

@RequestMapping(
        value = "/upload",
        method = RequestMethod.POST,
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE

)
public BankStatement uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
    return bankStatementService.uploadFile(file);
}

角度上传服务:

  uploadFile(file: File) {
    const formData = new FormData;
    formData.append('file', file);
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'multipart/form-data'
      })
      
    };

    return this.http.post<any>(this.apiUrl2 + 'upload', formData, httpOptions);
  }

Angular 上传组件.ts:

export class UploadComponent implements OnInit{
  uploadForm: FormGroup ;
  selectedFile: File | null = null;
  pdfUrl: string | null = null;

  
  constructor(private fb: FormBuilder, private dataService : DataService) {
    this.uploadForm = this.fb.group({
      file: [null, [Validators.required]]
    })
  }
  ngOnInit(): void {
    
  }

onSelectFile(event: any): void {
    this.selectedFile= event.target?.files[0];
  
  }

  uploadFile(){
    if (this.selectedFile) {
      const formData = new FormData;
      formData.append('file',this.selectedFile.name)
      this.dataService.uploadFile(this.selectedFile).subscribe(
        (response) => {
          console.log('File uploaded successfully!', response);
         
          this.pdfUrl = response.url; 
        },
        (error) => {
          console.error('Error uploading file:', error);
        }
      );
    }
  }

这是我在此过程中得到的结果:

enter image description here

enter image description here

angular spring-boot file-upload http-status-code-500
1个回答
0
投票

这条线可能是问题所在?

之前:

const formData = new FormData;

之后:

const formData = new FormData();
© www.soinside.com 2019 - 2024. All rights reserved.