If you are building an app that requires files to be uploaded on server you will need to follow this method. By using this method, you will be able to upload a file from your SD Card.
We will be using httpmime-4.2.5.jar for this tutorial. You can download it from here. Extract the zip file and you will find jar file under lib folder.
We will be using httpmime-4.2.5.jar for this tutorial. You can download it from here. Extract the zip file and you will find jar file under lib folder.
- Create a new android project in Eclipse, and add the jar file to lib folder.
- Add android.permission.INTERNET and android.permission.WRITE_EXTERNAL_STORAGE in your manifest file.
- Use the following code :
String address; MultipartEntity entity; File f; FileBody fb; entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); address = Environment.getExternalStorageDirectory() + "/temp.dat"; f = new File(address); fb = new FileBody(f, "application/octect-stream"); entity.addPart("file", fb); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("Your URL Here"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( response.getEntity().getContent())); StringBuffer stringBuffer = new StringBuffer(""); String line = ""; String LineSeparator = System.getProperty("line.separator"); while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + LineSeparator); } bufferedReader.close(); return stringBuffer.toString(); } catch (ClientProtocolException e) { return e.toString(); } catch (IOException e) { return e.toString(); }
f = new File(address);
fb = new FileBody(f, "application/octect-stream"); entity.addPart("file", fb);
We select the file given by address and then we get filebody using the FileBody Class and then add it to the entity.
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("Your URL Here"); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost);
Now android does not allow us to use network operations under the main thread, either we have to create a new thread or we use AsyncTask. You can Find the full source code here or download it here .
You can also use FTP library to uplaod the file which is better than this approach as described here.
Ads :
Buy Hard Drive, RAM, CD, DVD, USB on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my
Buy Hard Drive, RAM, CD, DVD, USB on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my
i want one demo src
ReplyDeletecode in android
Link is attached with post : http://www.mediafire.com/view/?icju1t5kq6i64em
Delete