繁体   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