2011-12-01 39 views
0

我想通过目标c中的php上传视频。我为android做了同样的事情,但是在目标c中,文件没有上传。平等客观的C代码

到我的PHP整个呼叫是:

- (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); 

} 

在Android的同一PHP中的调用是:

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(); 
      } 
    } 
} 

的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; 
} 
?> 

各自的日志后上传是:

的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 

安卓

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 

有人请让我知道什么是在目标下,相同的PHP在Android平台的原因,而不是。

回答

0

为什么你要创建这么大的缓冲区?无论如何,数据都以较小的块读取。


InputStream in; //FileInputStream 
OutputStream out; //DataOutputStream 

byte[] buffer = new byte[10 * 1024]; //or anything bigger you want 

int bytesRead; 

while ((bytesRead = in.read(buffer, 0, buffer.length) > 0)) { 
    out.write(buffer, 0, bytesRead); 
} 

在Objective-C:


#define BUFFER_SIZE 10 * 1024 

NSFileHandle* fileHandle; //file handle 
NSMutableData* out; //data buffer 

char buffer[BUFFER_SIZE]; 
ssize_t bytesRead; 

while ((bytesRead = read([fileHandle fileDescriptor], buffer, BUFFER_SIZE) > 0) { 
    [out appendBytes:buffer length:(NSUInteger) bytesRead]; 
} 

当然,你也可以使用NSFileHandle其他方法(见马塞洛阿尔维斯的答案)。无论如何,阅读整个文件,不要浪费时间阅读文件大小,这是没有必要的。

+0

谢谢...我是真正的着急,这解决了这个问题 –

+0

在收到警告@而(...),不兼容的整数指针转换传递的int类型的参数“FILE *' –

+0

我的不好。我从记忆中写下了它。现在它已经修复了。 – Sulthan

1

检查NSFileHandle类和readDataOfLength方法。您也可以检查attributesOfItemAtPath:error方法NSFileManager以获取文件大小。

+0

谢谢... NSFileHandle是真正有用的 –