如何知道多部分请求中部分的真实内容类型是什么

How to know what is the real content type of the part in multipart request

我正在从我的客户端向我的服务器发送一个多部分请求,如下所示:

FileBody file2 = new FileBody(new File("./test2.txt"));
FileBody image1 = new FileBody(new File("./DSC_0064.JPG"));

如您所见,其中一个文件是 txt,另一个是 JPG 图片。

在服务器上,我收到请求并为每个部分取 headers,我得到:

------------Part 1------------
content-disposition=form-data; name="test2"; filename="test2.txt"
content-type=application/octet-stream
content-transfer-encoding=binary
------------Part 2------------
content-disposition=form-data; name="image1"; filename="DSC_0064.JPG"
content-type=application/octet-stream
content-transfer-encoding=binary

如您所见,它们的内容类型都是 application/octet-stream。如何在动态环境中确定实际类型?是图像吗?文字?视频?

我不能依赖文件名,因为用户可以将它从 txt 更改为 png,然后我的服务器会认为它是一个图像,但他会因此例外。

那是因为您没有设置 MIME 类型。您可以使用另一个采用内容类型的构造函数 FileBody(file, contentType)

FileBody file2 = new FileBody(new File("./test2.txt"), ContentType.TEXT_PLAIN);
FileBody image1 = new FileBody(new File("./DSC_0064.JPG"), ContentType.create("image/jpeg"));