I need to send(upload) a jpeg image to a Servlet and rather than saving it on file, I want to turn it into a BufferedImage and do some processing on it.
This is my code for the client side:
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9000/upload");
File file = new File("/tmp/lena.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", 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();
How can I receive the image in a Servlet and process it?
I tried this on my receiving side Servlet, but the image is null:
InputStream is = request.getInputStream();
BufferedImage bImageFromConvert = ImageIO.read(is);
Finally, I should not save anything on disk in the process.
try:
Part file = request.getPart("userfile");
InputStream is = file.getInputStream();
Related
Im sending data using MulitpartEntity, I know zip file is being sent, I can loop it in php but for some reason the type returns empty.
if($_FILES["imagezip"]["name"]) {
$type = $_FILES["imagezip"]["type"];
$strLog .= $type . " type\n";
}
it keeps on failing when I try to move it
if(move_uploaded_file($_FILES['imagezip']['tmp_name'], $file_path)) {
$strLog .= "success\n";
} else{
$strLog .= "fail\n";
}
Here is how I am sending the file
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url); // You can use get method too here if you use get at the php scripting side to receive any values.
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("json", new StringBody(mPost));
multipartEntity.addPart("imagezip", new FileBody(mfile));
httpPost.setEntity(multipartEntity);
//httpPost.setEntity(new UrlEncodedFormEntity(parmeters));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
I have this code to post data to my server:
// HTTP Settings
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://myserver.com/Login");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// Http Headers
postRequest.addHeader("Accept", "application/xml");
postRequest.addHeader("Connection", "keep-alive");
// Credentials
reqEntity.addPart("username", new StringBody(ServerData.username));
reqEntity.addPart("password", new StringBody(ServerData.password));
if (m_sigFile.exists()) {
Bitmap m_sig = BitmapFactory.decodeFile(sigFilePath
+ "m_sig.jpg");
ByteArrayOutputStream m_bao = new ByteArrayOutputStream();
m_sig.compress(Bitmap.CompressFormat.JPEG, 90, m_bao);
byte[] m_ba = m_bao.toByteArray();
String m_ba1 = Base64.encodeToString(m_ba, 0);
reqEntity.addPart("m_sig.jpg", new StringBody(m_ba1));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
The code works perfectly, all data is send to the server except for the jpeg file. The server only accepts the file if I set the content type to 'image/jpeg', but only for the image. The username and password has to be in plain text. Is this possible?
This will work:
ContentBody cbFile = new FileBody(new File(myPath
+ "image_1.jpg"),
"image/jpeg");
reqEntity.addPart("photo1"), cbFile);
Don't forget to check if you file exists!
There is a constructor for StringBody that accepts content type:
new StringBody(titleString, "application/atom+xml", Charset.forName("UTF-8"));
How to send Image or Video with post request with lot off other parameters with post request ? I have image and video in byte[] format and I am trying like
HttpClient httpClient = new DefaultHttpClient();
http.setURI(URI.create(url));
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(),
a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
http.setEntity(reqEntity);
HttpResponse response = httpClient.execute(http);
it pass through code but it doesn't upload anything ( bab !=null ). Does anybody have any idea what is wrong, I cannot provide more info, other team is at ws ?
Your code should look something more like this:
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(), a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
HttpPost postMethod = new HttpPost(url);
postMethod.setEntity(reqEntity);
HttpClient httpClient = new DefaultHttpClient():
HttpResponse response = httpClient.execute(postMethod);
i just wanted to ask about sending gzip for post requests using HttpClient in Android?
where to get that OutputStream to be passed in the GZIPOutputstream?
any snippets?
Hi UseHttpUriRequest as shown below
String urlval=" http"//www.sampleurl.com/";
HttpUriRequest req = new HttpGet(urlval);
req.addHeader("Accept-Encoding", "gzip");
httpClient.execute(req);
and then Check response for content encoding as shown below :
InputStream is = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
is = new GZIPInputStream(is);
}
If your data is not too large, you can do it like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(POST_URL);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(baos);
gos.write(data.getBytes());
gos.close();
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(baos.toByteArray());
httpost.setEntity(byteArrayEntity);
I'm using httpclient to download images from a webpage and I'm trying to save them to disk but not having much luck. I'm using the code below to fetch the image but not sure what needs to be done next to actually get it to disk, the fetch would be on a JPG or a PNG image path... thanks
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,HttpClientFetch.emptyCookieStore);
HttpGet httpget = new HttpGet(pPage.imageSrc);
HttpResponse response;
response = httpClient.execute(httpget, localContext);
Header[] headers = response.getAllHeaders();
for(Header h: headers) {
logger.info("HEADERS: "+h.getName()+ " value: "+h.getValue());
}
HttpEntity entity = response.getEntity();
Header contentType = response.getFirstHeader("Content-Type");
byte[] tmpFileData;
if (entity != null) {
InputStream instream = entity.getContent();
int l;
tmpFileData = new byte[2048];
while ((l = instream.read(tmpFileData)) != -1) {
}
}
tmpFileData should now hold the bytes of the jpg from the website.
if (entity != null) {
InputStream instream = entity.getContent();
OutputStream outstream = new FileOutputStream("YourFile");
org.apache.commons.io.IOUtils.copy(instream, outstream);
}
Better use Apache commons-io, then you can just copy one InputStream to one OutputStream (FileOutputStream in your case).
Have a look at FileOutputStream and its write method.
FileOutputStream out = new FileOutputStream("outputfilename");
out.write(tmpFileData);