Category Archives: Uploaing a File

NSURLConnection – A Simple example – Upload image to server using POST method.

Make sure you setup the server and have gone through this post before reading this article.

You can read more about NSURLConnection Class from here.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/instm/NSURLConnection/

Here In this article I am going to select an image from the gallery and upload to a server using

1. Synchronous method
2. Asynchronous method – different ways.

First you have to make an interface like the below screenshot.
5 buttons, 1 Imageview and a label.
Make sure you hook all the controls to their respective labels and corresponding functions.

Upload Image To server using NSURLConnection

Upload Image To server using NSURLConnection

Now to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate, NSURLConnectionDelegate>{

    IBOutlet UILabel *response;
    NSMutableData *_responseData;
    
}


@property (strong, nonatomic) IBOutlet UIImageView* imageView;

- (IBAction) pickImage:(id)sender;


@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSData *pngData;
    NSData *syncResData;
    NSMutableURLRequest *request;
    UIActivityIndicatorView *indicator;
    
    #define URL            @"http://localhost/UploadImage/Upload_Image.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_IMAGE      @"NO IMAGE SELECTED"
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    pngData = nil;
    [self initPB];
}

- (IBAction) pickImage:(id)sender{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void) imagePickerController:(UIImagePickerController *)picker
         didFinishPickingImage:(UIImage *)image
                   editingInfo:(NSDictionary *)editingInfo
{
    self.imageView.image = image;
    pngData = UIImagePNGRepresentation(image);
    [self dismissModalViewControllerAnimated:YES];
}

-(BOOL) setParams{
    
    if(pngData != nil){
        
        [indicator startAnimating];
        
        request = [NSMutableURLRequest new];
        request.timeoutInterval = 20.0;
        [request setURL:[NSURL URLWithString:URL]];
        [request setHTTPMethod:@"POST"];
        
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:@"User-Agent"];
        
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"%@.png\"\r\n", @"Uploaded_file"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[NSData dataWithData:pngData]];
        
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        
        [request setHTTPBody:body];
        [request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
        
        return TRUE;
        
    }else{
        
        response.text = NO_IMAGE;
     
        return FALSE;
    }
}

- (IBAction) uploadImageSync:(id)sender
{
    
    if( [self setParams]){
        
        NSError *error = nil;
        NSURLResponse *responseStr = nil;
        syncResData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseStr error:&error];
        NSString *returnString = [[NSString alloc] initWithData:syncResData encoding:NSUTF8StringEncoding];
        
        NSLog(@"ERROR %@", error);
        NSLog(@"RES %@", responseStr);
        
        NSLog(@"%@", returnString);
        
        if(error == nil){
            response.text = returnString;
        }
    
        [indicator stopAnimating];
    
    }
    
}

- (IBAction) uploadImageAsync1:(id)sender
{

     if( [self setParams]){
    
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        
        // Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:queue
                               completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error){
                                   NSLog(@"Completed");
                                   
                                   response.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   
                                   [indicator stopAnimating];
                                   [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
                                   
                                   if (error) {
                                       NSLog(@"error:%@", error.localizedDescription);
                                   }
                                  
                               }];
     }
    

}

- (IBAction) uploadImageAsync2:(id)sender{
    
     if( [self setParams]){
    
         // Returns an initialized URL connection and begins to load the data for the URL request.
         if([[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]){
         
         };
         
     }
    
}

- (IBAction) uploadImageAsync3:(id)sender{
    
    if( [self setParams]){
        
       //Creates and returns an initialized URL connection and begins to load the data for the URL request.
        
        if([NSURLConnection connectionWithRequest:request delegate:self]){
            
        };
    }
    
}

-(void) initPB{
    indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width)/2, ([UIScreen mainScreen].bounds.size.height)/2 , 40.0, 40.0);
    indicator.center = self.view.center;
    [self.view addSubview:indicator];
    [indicator bringSubviewToFront:self.view];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    
    
    response.text = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    NSLog(@"_responseData %@", response.text);
    
    [indicator stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
    
    NSLog(@"didFailWithError %@", error);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

Now we go to the server side.

Please note the server file path in the code.
You must create a directory named “uploads” in the server before running the application.
Also Make sure that your server is running before you execute.

Refer the below Screenshot.

Upload Image To server using NSURLConnection

<?php
$target_path1 = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']).
    " has been uploaded to ".$target_path1;;
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
    echo "target_path: " .$target_path1;
}
?>

You can download the complete source code from here.

Upload Image To server using NSURLConnection

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to download a file from a remote site in android? – Another simple example – Method -3

Hello all …….

I have shown many examples on how to download and upload files in android through this site.

These are other methods for downloadign a file in android.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

I have shown four methods to upload an image to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.
4. How to upload an image from Android device to server? – Method 4

This is yet another example on how to do download a file.

So this is the java code that downloads the file.

package com.coderzheaven.pack;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadFileDemo extends Activity {
	
	String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
	String dest_file_path = "/sdcard/dwnloaded_file.png";
	Button b1;
	ProgressDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b1 = (Button)findViewById(R.id.Button01);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				dialog = ProgressDialog.show(DownloadFileDemo.this, "", "Downloading file...", true);
				 new Thread(new Runnable() {
			            public void run() {
			            	 downloadFile(dwnload_file_path, dest_file_path);
			            }
			          }).start();				
			}
		});
    }
    
    public void downloadFile(String url, String dest_file_path) {
    	  try {
    		  File dest_file = new File(dest_file_path);
    	      URL u = new URL(url);
    	      URLConnection conn = u.openConnection();
    	      int contentLength = conn.getContentLength();

    	      DataInputStream stream = new DataInputStream(u.openStream());

	          byte[] buffer = new byte[contentLength];
	          stream.readFully(buffer);
	          stream.close();

	          DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
	          fos.write(buffer);
	          fos.flush();
	          fos.close();
	          hideProgressIndicator();
	          
    	  } catch(FileNotFoundException e) {
    		  hideProgressIndicator();
    	      return; 
    	  } catch (IOException e) {
    		  hideProgressIndicator();
    	      return; 
    	  }
    }
    
    void hideProgressIndicator(){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	dialog.dismiss();
		    }
		});  
    }
}

This is the xml file that contains the button.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
    />
<Button 
	android:text="Download File" 
	android:id="@+id/Button01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Note : Please add these two permissions in the AndroidManifest.xml

  <uses-permission android:name="android.permission.INTERNET"/>    
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

download file android

download file android

Please leave your comments and also share this post if you like it.

ANDROID – Upload an image to a server

Hi ANDROIDians in today’s tutorial I will show you how to send an image to server using POST method in ANDROID.
Uploading an image to server is a basic requirement in many of our application.
Sending data to server which is using a PHP Script is already explained in this example .
Now in this example I will show you how to send an image file.
For that first we have to read the file, put it in nameValuePairs and then send using HttpPost.

I have already shown you three other methods on uploading a file to server. If you want you can check these posts.
1. How to Upload Multiple files in one request along with other string parameters in android?
2. Uploading audio, video or image files from Android to server.
3. How to upload an image from Android device to server? – Method 4

These are for downloading files from the server.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

Now can we quickly go to the code.

This is the main java file source code UploadImage.java

package pack.coderzheaven;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;

public class UploadImage extends Activity {
	InputStream inputStream;
	    @Override
	public void onCreate(Bundle icicle) {
	        super.onCreate(icicle);
	        setContentView(R.layout.main);

	        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);	        ByteArrayOutputStream stream = new ByteArrayOutputStream();
	        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
	        byte [] byte_arr = stream.toByteArray();
	        String image_str = Base64.encodeBytes(byte_arr);
	        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

	        nameValuePairs.add(new BasicNameValuePair("image",image_str));

	         Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				  try{
			             HttpClient httpclient = new DefaultHttpClient();
			             HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php");
			             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			             HttpResponse response = httpclient.execute(httppost);
			             String the_string_response = convertResponseToString(response);
			             runOnUiThread(new Runnable() {
				      			
				      			@Override
				      			public void run() {
				      				Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();		      				
				      			}
				      		});
			             
			         }catch(Exception e){
			        	  runOnUiThread(new Runnable() {
			      			
			      			@Override
			      			public void run() {
			      				Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();			      				
			      			}
			      		});
			               System.out.println("Error in http connection "+e.toString());
			         }	
			}
		});
         t.start();
	    }

	    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

	    	 String res = "";
	    	 StringBuffer buffer = new StringBuffer();
	    	 inputStream = response.getEntity().getContent();
             int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
              runOnUiThread(new Runnable() {
   			
   			@Override
   			public void run() {
   				Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();	      				
   			}
   		});
         
             if (contentLength < 0){
             }
             else{
	                byte[] data = new byte[512];
	                int len = 0;
	                try
	                {
		                while (-1 != (len = inputStream.read(data)) )
		                {
		                	buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
		                }
	                }
	                catch (IOException e)
	                {
	                	e.printStackTrace();
	                }
	                try
	                {
	                	inputStream.close(); // closing the stream…..
	                }
	                catch (IOException e)
	                {
	                	e.printStackTrace();
	                }
	                res = buffer.toString();	 // converting stringbuffer to string…..

	                runOnUiThread(new Runnable() {
           			
           			@Override
           			public void run() {
           			   Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show();
           			}
           		});
	                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
             }
	         return res;
	    }
}

Note : You should do networks operations inside a thread only.
AND you cannot modify UI elements inside a thread, but you have to do inside a UIThread only.

Now download a file from here which encodeBytes in Base64 Format. Put this file in the same package of UploadImage.java. See the screenshot.

Upload Image

Upload Image

However you can put in your own package but don’t forget to change the package name otherwise you will get error.

Now the server part.

Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this code into it.

I am saying the htdocs folder because I am using XAMPP. You change this according to your use.

<?php
	$base=$_REQUEST['image'];
	 $binary=base64_decode($base);
	header('Content-Type: bitmap; charset=utf-8');
	$file = fopen('uploaded_image.jpg', 'wb');
	fwrite($file, $binary);
	fclose($file);
	echo 'Image upload complete!!, Please check your php file directory……';
?>

Now run your program and check the folder in which your php file resides.
Note: Make sure your server is running.
Here I am uploading the icon image itself.

If you want to upload another file in your SDCARD you have to change this line to give the exact path

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);

For example if I have to upload a file residing in my SDCARD I would change the path like this.

Bitmap bitmap = BitmapFactory.decodeFile(“/sdcard/android.jpg”);

This tutorial explains how to create an SDCARD and start the emulator with the SDCARD
and this tutorial explains how to put file inside your emulator SDCARD

if you want to use the android using php and mysql
please check these posts.

1. Android phpMysql connection
2. Android phpmySQL connection redone.

Please comment if you didn’t get it right or you like this post.