簡體   English   中英

出現“不存在所需的請求部分'文件'”錯誤

[英]Getting “Required request part 'file' is not present” error

當我嘗試從Angular前端向Java Spring發送PUT請求時,收到“ Required request part 'file' is not present錯誤。 我在FormData中將名稱命名為“文件”,但我認為它似乎不像那樣。

當我在郵遞員中使用相同的PUT請求時,它確實起作用。

這是我的服務,其他方法也可以使用:

@Injectable()
export class ExamService {
  examens: Examen[] = [];

  constructor(private http: HttpClient) {}

  getExams(): Observable<Examen[]> {
    return this.http.get<Examen[]>(APIURL + '/all');
  }

  getExamById(id): Observable<Examen> {
    return this.http.get<Examen>(APIURL + '/asobject/' + id);
  }

  updateExamById(id, exam: Examen) {
    const fd = new FormData();
    console.log(exam.file);
    fd.append('name', exam.naam);
    fd.append('file', exam.file);
    return this.http.put<Examen>(APIURL + '/update/' + id, fd);
  }
}

這是我要發送的有效負載,因此似乎可以正確發送:

------WebKitFormBoundarynGgRxEgh6IdsxOiR
Content-Disposition: form-data; name="name"

Exam1
------WebKitFormBoundarynGgRxEgh6IdsxOiR
Content-Disposition: form-data; name="file"

4.868,68
------WebKitFormBoundarynGgRxEgh6IdsxOiR--

我的Spring控制器應該沒錯,因為Postman確實可以工作:

@PutMapping(value = "/update/{id}", consumes = "multipart/form-data")
public ResponseEntity UpdateExam(@RequestParam("file") MultipartFile file, @RequestParam("name") String name, @PathVariable("id") int id)
{
    Exam newExam = new Exam();
    newExam.setId(id);
    newExam.setSkelet(file.getOriginalFilename());
    newExam.setNaam(name);
    newExam.setCreatedAt(LocalDateTime.now());
    Exam exam2 = ExamFactory.update(newExam);
    examRepository.save(exam2);
    storageService.store(file);
    return created(URI.create("/skelet/exam/update/" + newExam.getId())).build();
}

您以錯誤的方式附加文件...請使用以下方式:

this.formData.append('file', file, file.name);

名稱

數據包含在值中的字段的名稱。

字段的值。 這可以是USVString或Blob(包括子類,例如File)。

文件名可選

當將Blob或File作為第二個參數傳遞時,報告給服務器的文件名(USVString)。 Blob對象的默認文件名是“ blob”。 File對象的默認文件名是文件的文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM