Я использую команду CURL, которая работает нормально (также Postman):
Код: Выделить всё
curl -X POST \
-F "files=@/path/to/my/file" \
-F "param1=someValue" \
"http://localhost:8000/my_endpoint"
Код: Выделить всё
with open(input_file, "rb") as file:
response = client.post(
url="/my_endpoint",
data={"param1": "someValue"},
files=[("files", file)],
)
Журналы сервера FastAPI показывают:
Код: Выделить всё
Did not find boundary character 121 at index 4
INFO: 127.0.0.1:60803 - "POST /transcribe HTTP/1.1" 400 Bad Request
Код: Выделить всё
String boundary = UUID.randomUUID().toString();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create(myUrl))
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.version(HttpClient.Version.HTTP_1_1)
.POST(HttpRequest.BodyPublishers.ofByteArray(createFormData(multipartFile)))
.build();
HttpResponse resp = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
Код: Выделить всё
private byte[] createFormData(MultipartFile multipartFile) throws IOException {
HttpEntity httpEntity = createMultipartFile(multipartFile);
return getByteArray(httpEntity);
}
public HttpEntity createMultipartFile(MultipartFile multipartFile) {
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
byte[] fileBytes = multipartFile.getBytes();
ByteArrayBody fileBody = new ByteArrayBody(fileBytes, ContentType.DEFAULT_BINARY, multipartFile.getName());
builder.addPart("files", fileBody);
builder.addPart("param1", new StringBody("someValue", ContentType.TEXT_PLAIN));
// Set the multipart entity to the request
return builder.build();
} catch (IOException e) {
throw new MyException(e);
}
}
public byte[] getByteArray(HttpEntity multipartEntity) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
multipartEntity.writeTo(baos);
return baos.toByteArray();
} catch (IOException e) {
throw new MyException(e);
}
}
Код: Выделить всё
.header("Content-Type", "multipart/form-data; boundary=" + boundary)Как решить эту проблему и успешно отправить данные составной формы из моего Java-клиента на сервер FastAPI?< /п>
Подробнее здесь: https://stackoverflow.com/questions/781 ... -form-data
Мобильная версия