How to send list of files by RESTEasy java - java

How can we send list of files by RESTEasy java client?
Spring REST is:
#PostMapping()
public ResponseEntity<?> send(#RequestPart(value = "message") String message, #RequestPart(value = "attachment", required = false) List<MultipartFile> attachments)
In Postman it is made by specifying multiple files in form-data with one key "attachment", but MultipartFormDataOutput has Map inside, so it remembers only the last added file.

I have resolved this problem with using org.apache.http.entity.mime.MultipartEntityBuilder:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("message", messageStr, ContentType.TEXT_PLAIN.withCharset(UTF_8));
for (File file: files) {
builder.addBinaryBody(
"attachment",
new FileInputStream(file),
ContentType.APPLICATION_OCTET_STREAM,
file.getName()
);
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(url);
uploadFile.setEntity(builder.build());
CloseableHttpResponse response = httpClient.execute(uploadFile);

Related

slack api : files to upload to slack channel

I'm trying to publish image from my automation suite to slack channel.
URL to hit: https://slack.com/api/files.upload
Body is form-data type and it has,
file - image file upload
initial_comment - some string
channels - the slack channel to be published.
i tried using MultipartEntity class inside HttpPost
MultipartEntity multiPartEntity = new MultipartEntity();
FileBody fileBody = new FileBody(file);
//Prepare payload
multiPartEntity.addPart("file", fileBody);
multiPartEntity.addPart("file_type", new StringBody("JPG"));
multiPartEntity.addPart("initial_comment", new StringBody("cat shakes"));
multiPartEntity.addPart("channels", new StringBody("bot-e2e-report"));
//Set to request body
postRequest.setEntity(multiPartEntity);
Im getting the success response from http post. but the image is not posted in slack channel.any help!
The problem was with header. Actually, this slack api gives 200 response even for the wrong header. Working code:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
//Set various attributes
MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create();
entitybuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entitybuilder.addBinaryBody("file", file);
entitybuilder.addTextBody("initial_comment", "cat");
entitybuilder.addTextBody("channels","bot-e2e-report");
HttpEntity mutiPartHttpEntity = entitybuilder.build();
RequestBuilder reqbuilder = RequestBuilder.post("https://slack.com/api/files.upload");
reqbuilder.setEntity(mutiPartHttpEntity);
//set Header
reqbuilder.addHeader("Authorization", "Bearer xoxb-16316687382-1220823299362-fdkBklPrY7rc72bQk3WSOSjD");
HttpUriRequest multipartRequest = reqbuilder.build();
// call post
HttpResponse response = httpclient.execute(multipartRequest);
// Parse the response
HttpEntity entity = response.getEntity();
String json = EntityUtils.toString(entity, StandardCharsets.UTF_8);
System.out.println(json);

Upload File from GWT to another domain , response is always null

I am uploading a File from GWT to a different domain
File Uploads well , But the response i sent from the server always reaches as "null" at the client side
response.setContentType("text/html");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().print("TEST");
response is NULL only when i upload the file on a different domain ... (on same domain all is OK)
I also see this in GWT documentation
Tip:
The result html can be null as a result of submitting a form to a different domain.
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FormPanel.SubmitCompleteEvent.html
Is there any way I can receive back a response at my client side when i am uploading file to a different domain
There are 2 possible answer:
Use JSONP Builder
JsonpRequestBuilder requestBuilder = new JsonpRequestBuilder();
requestBuilder.requestObject(url, new AsyncCallback<FbUser>() {
#Override
public void onFailure(Throwable ex) {
throw SOMETHING_EXCEPTION(ex);
}
#Override
public void onSuccess(ResponseModel resp) {
if (resp.isError()) {
// on response error on something
log.error(resp.getError().getMessage())
log.error(resp.getError().getCode())
}
log.info(resp.getAnyData())
}
Not to use GWT to upload, rather use other client like apache HttpClient
public uploadFile() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
FileBody bin = new FileBody(new File(UPLOADED_FILE));
long size = bin.getContentLength();
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("PART", bin);
String content = "-";
try {
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity ent = response.getEntity();
InputStream st = ent.getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(st, writer);
content = writer.toString();
} catch (IOException e) {
return "false";
}
return content;
}
Hope it helps

POST two InputStreams in a javax Request

I'm trying to send a request to an endpoint that takes a form with two files. The method I'm currently trying fails on the last line:
WebTarget client = myUtils.createClient(URL, ENDPOINT);
MultivaluedMap<String, InputStream> formData = new MultivaluedHashMap<>();
formData.add(FILE_1, stream1);
formData.add(FILE_2, stream2);
Entity<MultivaluedMap<String, InputStream>> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA_TYPE);
Response response = client.request().post(entity);
The error reached is
javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type multipart/form-data type: javax.ws.rs.core.MultivaluedHashMap
Changing MediaType to APPLICATION_FORM_URLENCODED_TYPE yields
java.lang.ClassCastException: java.io.SequenceInputStream cannot be cast to java.lang.String
Is there a better way to handle POSTing a form with two files?
There are multiple ways.
If you are using Jersey, One way is to do something like:
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
....
....
FileDataBodyPart fileDataBodyPart =
new FileDataBodyPart("file", new File("/filelocation/file.txt"));
FormDataMultiPart formDataMultiPart = (FormDataMultiPart)
FormDataMultiPart.field("somekey","somevalue")
.bodyPart( fileDataBodyPart);
WebTarget target = client.target(restServiceURLYouwant);
Response response = target.request().post(Entity.entity(formDataMultiPart,
formDataMultiPart.getMediaType()));
formDataMultiPart.close();
Another way is to use Apache HttpUtils
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
....
....
MultipartEntity multipartEntity = new MultipartEntity();
FileBody fb = new FileBody(file, "application/octet-stream");
multipartEntity.addPart(fb);
HttpClient httpClient = new DefaultHttpClient() ;
HttpPost httpPostRequest = new HttpPost (url) ;
//url above should be url of the Rest service endpoint
httpPostRequest.setEntity(multiPartEntity) ;
              
 HttpResponse response = httpClient.execute(httpPostRequest) ;

Java : Send Multipart File to RESTWebservice

I am using Spring as Technology. Apache HttpClient for calling Webservice. Basic purpose is to upload Multipart File(File is not any image file or video file). but Here My requirement is slightly different. Kindly check below image.
Here You can see first block. It is a simple GUI, having only 2 input tags along with proper form tag.
In second block, There is RESTFul Webservice, which takes Multipart File as parameter and process it. (Upto this it is done).
Now I am stuck here. I want to send this Multipart File to other RESTFul Webservice which consumes Multipart File only.
code Snippet of RESTFUL Webservice : (Commented some questions, need your suggestion)
#RequestMapping(value="/project/add")
public #ResponseBody String addURLListToQueue(
#RequestParam(value = "file") MultipartFile file,
#RequestParam(value = "id1", defaultValue = "notoken") String projectName,
#RequestParam(value = "id2", defaultValue = "notoken") String id2,
#RequestParam(value = "id3", defaultValue = "notoken") String id3){
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:8080/fs/project/add");
// 1) Do I need to convert it into File object? (tried but faced 400 Error)
// 2) Is there any provision to send Multipart File as it is?
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "multipart/form-data");
mpEntity.addPart("file", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
Questions : How to send Multipart File to RESTFul Webservice using HttpClient?
Can you check this file upload apache http client?
Also
HttpPost post = new HttpPost("http://echo.200please.com");
InputStream inputStream = new FileInputStream(zipFileName);
File file = new File(imageFileName);
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody
("upfile", file, ContentType.DEFAULT_BINARY, imageFileName);
builder.addBinaryBody
("upstream", inputStream, ContentType.create("application/zip"), zipFileName);
builder.addTextBody("text", message, ContentType.TEXT_PLAIN);
//
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
Source

Creating a HTTP Server in Node.js service POST with file

I would like to order sent to the POST request with a parameter in the form of a JPG file.
I use HttpClient in version 4.4.1
Part of the Java code looks like this:
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
File file = new File("path_to_jpg");
HttpPost post = new HttpPost("http://localhost:1337/uploadJPG");
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
System.out.println(response.getEntity().getContent());
} finally {
httpclient.close();
}
next at "http://localhost:1337/uploadJPG" want to let nodeJS have a server that will process the JPG file
the idea of server code nodeJS:
var http = require('http'),
fs = require('fs'),
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
//process file JPG
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('processed JPG');
}
});
port = 1337;
host = '127.0.0.1';
server.listen(1337, '127.0.0.1');
console.log('Listening at http://' + '127.0.0.1' + ':' + 1337);
and now my question is, How can I create such a service in NodeJS, which will have the file in jpg?
Not sure if you are using Express or not but if you are you can use a middleware like Multer which makes it very simple to handle MultiPart data and files.

Categories