I am trying to upload videos through php in objective c. I have done the same for android but in objective c the files are not getting uploaded.
The entire call to my php is:
- (IBAction)uploadVideo {
/* setting up the URL to post to */
NSString *urlString = @"http://172.19.128.170/UploadFile.php";
/* setting up the request object */
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
/* setting up the request body*/
NSString *path = [[NSString alloc]init];
path = @"Users/msat/Library/ApplicationSupport/iPhoneSimulator/4.3.2/Media/DCIM/100APPLE/";
NSString *boundary = [NSString stringWithString:@"*****"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@", boundary, @"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"uploadeFfile\"; filename=\"Users/msat/Library/ApplicationSupport/iPhoneSimulator/4.3.2/Media/DCIM/100APPLE/IMG_0001.png""\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"--\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
// setting up the buffer size
int buffer[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = read([fileHandle fileDescriptor], buffer, BUFFER_SIZE) > 0)) {
[body appendBytes:buffer length:(NSUInteger)bytesRead];
}
[body appendData:[[NSString stringWithFormat:@"buffer"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type:"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@", boundary, @"--\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
/* setting the body of the post to the reqeust */
[request setHTTPBody:body];
/* setting up the connection to the web*/
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"...this is returned %@", returnData);
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"...this is uploaded %@", returnString);
}
The call to the same php in Android is:
public void onUpload(View v) {
Log.i("UploadFinal", "In onUpload of UploadFinalActivity ");
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = mFilePathTextView.getText().toString();//"/sdcard/Pictures/Mahindra Satyam.JPG";
Log.i("UploadFinal", "After getting existingFileName "+existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024*1024*1024;
//String responseFromServer = "";
String urlString = "";
if(phpPath!=null){
urlString = phpPath;
}else{
urlString = "_http://172.19.128.170/UploadFile.php";
}
//String urlString = "_http://172.19.128.170/sample.php";
Log.i("UploadFinal", "URL string is :"+urlString);
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
//dos.writeBytes("Content-Disposition: form-data; name=\"description\";filename=\"" + "hello" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
Log.i("UploadFinal", "bytesAvailable are :"+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i("UploadFinal", "bytesRead are :"+bytesRead);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
Log.i("UploadFinal", "bytesAvailable are :"+bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i("UploadFinal", "bytesRead are :"+bytesRead);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.i("UploadFinal","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error1: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error2: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.i("UploadFinal","Server Response "+str);
}
inStream.close();
if(uploadtype!=null){
Intent intent2=new Intent();
intent2.putExtra("uploadstatus", "Success");
setResult(RESULT_OK, intent2);
finish();
}
}
catch (IOException ioex){
Log.e("Debug", "error3: " + ioex.getMessage(), ioex);
if(uploadtype!=null){
Intent intent2=new Intent();
intent2.putExtra("uploadstatus", "Failed");
setResult(RESULT_OK, intent2);
finish();
}
}
}
The php:
<?php
$target_path = "./Videos/";
/* Add the original filename to our target path.
Result is "/tmp/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
echo "before checking the file!". basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " . $target_path;
}
?>
The Respective logs after uploading are:
Obj C:
before checking the file!.pngArray
(
[uploadedfile] => Array
(
[name] => .png
[type] =>
[tmp_name] =>
[error] => 3
[size] => 0
)
)
There was an error uploading the file, please try again!filename: .pngtarget_path: ./Videos/Unapproved/.png
Android:
12-07 11:54:23.775: INFO/UploadFinal(293): Server Response Entered the PHP file!!! Imagebefore checking the file!Mahindra Satyam.JPGArray
12-07 11:54:23.775: INFO/UploadFinal(293): Server Response (
12-07 11:54:23.775: INFO/UploadFinal(293): Server Response [uploadedfile] => Array
12-07 11:54:23.785: INFO/UploadFinal(293): Server Response (
12-07 11:54:23.795: INFO/UploadFinal(293): Server Response [name] => Mahindra Satyam.JPG
12-07 11:54:23.806: INFO/UploadFinal(293): Server Response [type] =>
12-07 11:54:23.825: INFO/UploadFinal(293): Server Response [tmp_name] => /tmp/phpgi8nVz
12-07 11:54:23.848: INFO/UploadFinal(293): Server Response [error] => 0
12-07 11:54:23.848: INFO/UploadFinal(293): Server Response [size] => 2762
12-07 11:54:23.856: INFO/UploadFinal(293): Server Response )
12-07 11:54:23.856: INFO/UploadFinal(293): Server Response
12-07 11:54:23.866: INFO/UploadFinal(293): Server Response )
12-07 11:54:23.886: INFO/UploadFinal(293): Server Response The file Mahindra Satyam.JPG has been uploaded ConnectedAfter insertion
Somebody please let me know what is the reason for which the same php is working in android and not in objective c.
Why do you create such a big buffer? The data is read in smaller chunks anyway.
In objective-c:
Of course, you can also use other methods on NSFileHandle (see Marcelo Alves’ answer). Anyway, to read entire file, don’t waste time reading file size, it’s not necessary.