繁体   English   中英

Equalhand目标C代码

[英]Equalhand Objective C code

我正在尝试在目标c中通过php上传视频。 我已经为android做过同样的事情,但是在目标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;
}
?>

上传后的各自日志为:

对象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 

有人请让我知道为什么相同的php在android中而不是在目标c中工作的原因是什么。

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

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


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上使用其他方法(请参见Marcelo Alves的答案)。 无论如何,要读取整个文件,不要浪费时间读取文件大小,这是没有必要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM