Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.61k stars 594 forks source link

byte[] uploads #91

Closed Jamesgt closed 5 years ago

Jamesgt commented 9 years ago

It would be nice to have also

public MultipartBody field(String name, byte[] bytesOfFile) { ... }

Then not only files written to disk can be sent, but also ones generated and kept only in memory.

varra4u commented 9 years ago

It's very surprising to see this as missing in such a good API !!!

Please add it as it would be like very handy for uploads!!

Thanks, Krishna

varra4u commented 9 years ago

For time being, I've edited the source code of com.mashape.unirest.request.body.MultipartBody and achieved it by adding the below method:

public MultipartBody field(String name, InputStream stream, ContentType contentType, String fileName) { return field(name, new InputStreamBody(stream, contentType, fileName), true, contentType.getMimeType()); }

public HttpEntity getEntity() { if (hasFile) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (mode != null) { builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); } for (String key : keyOrder) { List value = parameters.get(key); ContentType contentType = contentTypes.get(key); for (Object cur : value) { if (cur instanceof File) { File file = (File) cur; builder.addPart(key, new FileBody(file, contentType, file.getName())); } else if (cur instanceof InputStreamBody) { builder.addPart(key, (ContentBody) cur); } else { builder.addPart(key, new StringBody(cur.toString(), contentType)); } } } return builder.build(); } else { try { return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }

Jamesgt commented 9 years ago

Nice, you can help their work by creating a pull request with your changes.

SGrondin commented 9 years ago

Yes please submit a PR for this. Make sure to include some tests.

varra4u commented 9 years ago

I did pull request, can find the status at: https://github.com/Mashape/unirest-java/pull/93

ghost commented 9 years ago

Seeing inconsistent behavior on this pull request. The following works...

final HttpResponse resp = Unirest.post(url).header("accept", "application/json").field("file", file).asString();

However, when I change the file type from File to InputStream:

final HttpResponse resp = Unirest.post(url).header("accept", "application/json").field("file", is).asString();

I see errors in the netty web-service stating the file parameter isn't present...I doesn't seem that the "file" key is getting added to the request.

ryber commented 5 years ago

We do have one like this but it requires a file name.