Equalhand目标C code [英] Equalhand Objective C code
问题描述
我想通过目标C PHP上传视频。我也做了同样为Android,但在目标C文件没有得到上传
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.
我的PHP中的整个呼叫是:
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);
}
在Android的同一PHP中的调用是:
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();
}
}
}
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的:
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工作的原因。
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.
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的:
In 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方法(参见马塞洛阿尔维斯的回答)。总之,要读整个文件,不要浪费时间阅读文件的大小,这是没有必要的。
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.
这篇关于Equalhand目标C code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!