Posting A Single Image To Server Locally
I am trying for a simple image upload to local server What I am trying to do :: I am trying to upload one image to server on click of button I have referred this link But i don'
Solution 1:
Use the below an try
publicvoidpostData() {
BitmapbitmapOrg= BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
ByteArrayOutputStreambao=newByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
ArrayList<NameValuePair> nameValuePairs = newArrayList<NameValuePair>();
nameValuePairs.add(newBasicNameValuePair("image",ba1));
try{
HttpClienthttpclient=newDefaultHttpClient();
HttpPosthttppost=newHttpPost("http://10.0.2.2:7002/Details/");
httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));
HttpResponseresponse= httpclient.execute(httppost);
HttpEntityentity= response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
Edit:
Just for testing try uploading image from sdcard using file path
try
{
String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"Download"+File.separator+"ic_launcher.png";
HttpClienthttpclient=newDefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPosthttppost=newHttpPost("your url");
Filefile=newFile(filepath);
MultipartEntitympEntity=newMultipartEntity();
ContentBodycbFile=newFileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponseresponse= httpclient.execute(httppost);
HttpEntityentity= response.getEntity();
String _response=EntityUtils.toString(entity);
Log.i(".......",_response);
}catch(Exception e){
e.printStacktrace();
}
Solution 2:
Finally with the help of Raghunandan ...... from one of the answers .... found the solution
Ill post the complete answer so that .... this might be helpful to some-one
MainActivity.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
publicclassMainActivityextendsActivity {
Button submit;
ProgressDialog pDialog;
InputStream is;
ImageView imageView;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
imageView = (ImageView) findViewById(R.id.imageView1);
submit.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
// TODO Auto-generated method stubnewMainTest().execute();
}
});
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
* @throws IOException
*/publicvoidpostImageData() {
try
{
BitmapbitmapOrg= BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
HttpClienthttpClient=newDefaultHttpClient();
HttpPostpostRequest=newHttpPost("http://10.0.2.2:7002/Details/");
MultipartEntityreqEntity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStreambos=newByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBodybab=newByteArrayBody(data, "forest.jpg");
reqEntity.addPart("key", bab);
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", newStringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponseresponse= httpClient.execute(postRequest);
BufferedReaderreader=newBufferedReader(newInputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilders=newStringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
}catch(Exception e){
e.getStackTrace();
}
}
publicclassMainTestextendsAsyncTask<String, Integer, String> {
@OverrideprotectedvoidonPreExecute() {
pDialog = newProgressDialog(MainActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Overrideprotected String doInBackground(String... params) {
postImageData();
returnnull;
}
@OverrideprotectedvoidonPostExecute(String result) {
// TODO Auto-generated method stubsuper.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
}
ExpressJS code
app.js
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var app=express();
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
//.use(express.cookieParser());
app.use(express.bodyParser());
app.post('/Details/',function(req,res,next){
var file_name=req.files.key.originalFilename;
console.log(file_name);
crypto.randomBytes(8, function(ex, buf) {
vararray = req.files.key.originalFilename.split('.');
var type = array[array.length - 1];
var name = buf.toString('hex') + '.' + type;
fs.rename(req.files.key.path, './public/images/' + name, function(e) {
if (e) {
res.send(500, e.message);
} else
{
res.send("I got the message - This i confirm");
}
});
});
});
app.get('/Details/',function(req,res){
res.send("Image displayed");
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
Point to keep in mind ::
- Make sure you send data as multipart from client(android)
- Then make sure u accept data on server side also as multipart
Post a Comment for "Posting A Single Image To Server Locally"