I am using the ASIHTTPRequest framework trying to upload a file to my websever via iPhone.
Below is the code. As long as I don't use the setFile method, I get a 200 back from the server, so everthing is fine. As soon as I implement setFile, the server returns 0. I would expect a 401 or anything like this, as I could imagine that I deal with an authentication issue.
My server is an IIS, why I use the NTLM way in the request. Do I miss something?
NSInteger httpStatus;
NSString *httpResponseString;
NSError *httpRequestError;
NSArray *paths = [[[NSArray alloc] init] autorelease];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filename = [documentsDirectory stringByAppendingPathComponent:#"abiliator_basis_de_ar.xml"];
NSURL *myURL = [NSURL URLWithString: #"http://my.url.com/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:myURL];
[request setShouldPresentCredentialsBeforeChallenge:NO];
[request setUsername:#"myUserName"];
[request setPassword:#"myPassword"];
[request setDomain:#"myDomainName"];
[request setFile:[NSURL URLWithString:filename] forKey:#"xml"];
[request startSynchronous];
httpRequestError = [request error];
httpResponseString = [request responseString];
httpStatus = [request responseStatusCode];
if (!httpRequestError) {
httpStatus = [request responseStatusCode];
NSLog(#"Class %#, Method: %# - OK login and filetransfer successful '%i'", self.myClassName, NSStringFromSelector(_cmd), httpStatus);
}
else {
NSLog(#"Class %#, Method: %# - Error '%i' occurred sending the http request", self.myClassName, NSStringFromSelector(_cmd), httpStatus);
}
Yes the file exists, here the result from the ls:
rene-stegs-macbook-pro:~ renesteg$ ls -ltr '/Users/renesteg/Library/Application Support/iPhone Simulator/5.1/Applications/417BD791-64BC-48D0-B519-F10C7F617E36/Documents/abiliator_basis_de_ar.xml'
-rw-r--r--# 1 renesteg staff 1062 22 Mai 13:44 /Users/renesteg/Library/Application Support/iPhone Simulator/5.1/Applications/417BD791-64BC-48D0-B519-F10C7F617E36/Documents/abiliator_basis_de_ar.xml
And here the value of filename:
Filename string is: '/Users/renesteg/Library/Application Support/iPhone Simulator/5.1/Applications/417BD791-64BC-48D0-B519-F10C7F617E36/Documents/abiliator_basis_de_ar.xml
You are doing something wrong while uploading file.
it need to like this
NSFileManager *fileManager = [NSFileManager defaultManager];
request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:120];
[request setPostFormat:ASIMultipartFormDataPostFormat];
[request addRequestHeader:#"Content-Type" value:#"multipart/form-data"];
if ([fileManager fileExistsAtPath:filePath] == YES) {
[request setFile:filePath withFileName:#"test.xml" andContentType:#"xml" forKey:#"FieldName"];
}
Here file path need to set for fromdata request.
Hope this will work for you.
You should probably try usingsetData:forKey: and send the data of the xml file, example below..
.....
NSURL *myURL = [NSURL URLWithString: #"http://my.url.com/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:myURL];
[request setShouldPresentCredentialsBeforeChallenge:NO];
[request setUsername:#"myUserName"];
[request setPassword:#"myPassword"];
[request setDomain:#"myDomainName"];
[request setData:[NSData dataWithContentsOfFile:fileName] forKey:#"xml"];
[request startSynchronous];
.....
Also, you should probably make this an asynchronous request.
i think the error occurs because you should use:
[request setFile:[NSURL fileURLWithPath:filename] forKey:#"xml"];
Ok, the issue was between the line of Neels comment: missing PHP.
And this of course needs to be called in the URL, so the correct way to build the URL is:
NSURL *myURL = [NSURL URLWithString: #"http://my.url.com/upload.php"];
This way I got the mapping my iPhone httpRequest code and the PHP.
Here's the required PHP code:
<?php
$target = "upload/";
$target = $target . basename( $_FILES['xml']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['xml']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['xml']['name']). " has been uploaded";
}
else {
echo "Error uploading". basename( $_FILES['xml']['name']). " occured";
}
?>
Related
I'm trying to parse JSON Using ASIHttpRequset
I wrote this code
-(void) tryASIHttpRequest{
NSString *phpUrl = #"http://www.myURL.com/subfolder/myFile.php";
NSString *dbName = #"dbName";
NSString *localHost = #"localhost";
NSString *dbUser = #"dbUser";
NSString *dbPwd = #"password";
NSString *S_user_id = [NSString stringWithFormat:#"%d",u_id0];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setRequestMethod:#"POST"];
[request setPostValue:dbName forKey:#"dbName"];
[request setPostValue:localHost forKey:#"localHost"];
[request setPostValue:dbUser forKey:#"dbUser"];
[request setPostValue:dbPwd forKey:#"dbPwd"];
[request setPostValue:S_user_id forKey:#"user_id"];
[request setPostValue:#"" forKey:#"submit"];
[request setTimeOutSeconds:120];
[request setDelegate:self];
NSError *error = [request error];
[request startAsynchronous];
if (!error) {
NSData *response = [request responseData];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
NSString *bo_id2 = [status objectForKey:#"bo_id"];
NSString *bo_name2 = [status objectForKey:#"bo_name"];
NSLog(#"from server using ASIHttpRequest");
NSLog(#"bo_id: %# - bo_name: %#", bo_id2, bo_name2);
}
}else{
NSLog(#"ASIHttp Error: %#", error);
}
}
and in bookOwn.php I wrote the following
<?php
if (isset($_POST['submit'])) {
$dbName = $_POST['dbName'];
$localHost = $_POST['localHost'];
$dbUser = $_POST['dbUser'];
$dbPwd = $_POST['dbPwd'];
$user_id = $_POST['user_id'];
$con = mysql_connect($localHost,$dbUser,$dbPwd);
$db_found = mysql_select_db("iktab_book");
mysql_query('SET CHARACTER SET UTF8');
mysql_query("SET NAMES utf8; ");
$check = mysql_query("SELECT * FROM d_book where bo_id IN (Select Distinct(sal_bo_id) From d_sales Where sal_user_id =" . $user_id . ")");
while($row=mysql_fetch_assoc($check))
$output[]=$row;
$json_encode =json_encode($output);
$utf8_decode = utf8_decode($json_encode);
echo $json_encode;
mb_convert_encoding($json_encode, 'UTF-8');
$html_entity_decode = html_entity_decode($json_encode);
mysql_close();
}
?>
if the code is ok, this line will be printed
from server using ASIHttpRequest
but it doesn't print and I can't determine what is the wrong in my code.
Any help ?
Thanks in Advance.
It looks like you are doing an asynchronous request [request startAsynchronous]; and then are checking on the next line to see if there is data. Asynchronous means that it will be executed later on. Usually one would become the request's delegate to get notified when the request was finished loading.
More Pressing:
Don't use ASIHTTPRequest. It has been deprecated by its author. Note the banner on the website advising using something else
For alternative URL frameworks AFnetworking is popular.
Also NSURLConnection isn't that bad.
And finally if you are targeting iOS 5 or higher (and theres not much reason to support less) you no longer need SBJSON. NSJSONSerialisation is provided by the OS for converting JSON into objects and back again.
I am creating an app for jailbroken idevices and need the ability to install .debs into /Library/Themes/ I have looked everywhere for documentation or an example but with not to my surprise I found nothing of great use. I first want to grab the .deb from a URL then just simply install that package into the users folders. If anyone has had any experience with this or might can point me in the right direction that would be greatly appreciated.
Here is a similar question but never seemed to really get answered.
How to install a .deb file on a jailbroken iphone programmatically?
//SYCRONIZED REQUEST
- (IBAction)grabURL:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://freeappl3.com/com.freeapple.quickunlock_0.0.1-
25_iphoneos-arm.deb"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"responce String = %#",response);
}
}
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://freeappl3.com/com.freeapple.quickunlock_0.0.1-
25_iphoneos-arm.deb"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
NSString *path = #"/Library/Themes/";
[request setDelegate:self];
[request setDownloadDestinationPath:path];
[request setDownloadProgressDelegate:progress];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"responce String = %#",responseString);
// Use when fetching binary data
NSData *responseData = [request responseData];
NSLog(#"responce Data = %#",responseData);
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"responce Error = %#",error);
}
Logs
//when I use my method "grabUrl:"
!<arch>
debian-binary 1311198441 0 0 100644 4 `
2.0
control.tar.gz 1311198441 0 0 100644 381 `
/when I use my method "grabUrlInBackground:"
ThemeCatcher2[44212:16a03] responce Error = Error Domain=ASIHTTPRequestErrorDomain Code=8
"Failed to move file from '/var/folders/jw/j5qzb3b51s17ywd9m7vw52y40000gn/T/62973B18-B19A-
47FC-B2FB-A7E7F8C831AA-44212-00042A5738D4841E' to '/Library/Themes/'" UserInfo=0x9151ea0
{NSUnderlyingError=0x9151fa0 "The operation couldn’t be completed. (Cocoa error 4.)",
NSLocalizedDescription=Failed to move file from
'/var/folders/jw/j5qzb3b51s17ywd9m7vw52y40000gn/T/62973B18-B19A-47FC-B2FB-A7E7F8C831AA-
44212-00042A5738D4841E' to '/Library/Themes/'}
try using
system("/usr/bin/dpkg -i <filename_of_deb_including_extension>");
You'll need root privileges for this though.
:)
Use the following code
NSString *appsyncDebPath=#"/var/root/appsync.deb";
NSString *cmdString=[NSString stringWithFormat:#"/usr/bin/dpkg -i %# >/tmp/dpkg.log;",appsyncDebPath];
const char *cmdChar=[cmdString UTF8String];
system(cmdChar);
Before this, you should execute
setuid(0);
setgid(0);
I'm using ASIFormDataRequest for Post data then parsing with JSON. ASIHTTPRequest has built in caching using [ASIHTTPRequest setDefaultCache:[ASIDownloadCache sharedCache]];. Does anyone know if there is anything similar for ASIFormDataRequest?
Example:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/myapp/20110715/60b88126/load_dr_daily_schedule/%#/", [self getHost], [dateFormat stringFromDate:today]]];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[self addCurrentUserLoginToPostRequest:request];
[request setPostValue:[dateFormat stringFromDate:today] forKey:#"target_date"];
[request startSynchronous];
NSError *error = [request error];
NSString *responseString;
if (!error) {
responseString = [request responseString];
} else {
return NULL;
}
return [responseString JSONValue];
ASIFormDataRequest is a subclass of ASIHTTPRequest, so it was the same properties as ASIHTTPRequest.
Note that it won't cache POST requests though.
I try to download a file from my server, this is the code, on my console I see the xml file, but I can't save it.
Where is the problem for you?
- (IBAction)grabURL:(id)sender{
NSURL *url = [NSURL URLWithString:#"http://www.endurodoc.net/photo/data.xml"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"%#",response);
}
else{
NSLog(#"Errore");
}
//[request setDownloadDestinationPath:#"/Users/kikko/Desktop/data.xml"];
// SAVED PDF PATH
// Get the Document directory
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// Add your filename to the directory to create your saved pdf location
NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:#"data.xml"];
// TEMPORARY PDF PATH
// Get the Caches directory
NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// Add your filename to the directory to create your temp pdf location
NSString *tempPdfLocation = [cachesDirectory stringByAppendingPathComponent:#"data.xml"];
// Tell ASIHTTPRequest where to save things:
[request setTemporaryFileDownloadPath:tempPdfLocation];
[request setDownloadDestinationPath:pdfLocation];
}
You need to put:
[request setTemporaryFileDownloadPath:tempPdfLocation];
[request setDownloadDestinationPath:pdfLocation];
before:
[request startSynchronous];
ASIHTTPRequest does the file saving when the request is made, so if you set those properties after the request has already happened then nothing will happen.
I am using ASIHTTPRequest for downloading file from server but its giving error
Failed to move file from '/Users/admin/Library/Application
Support/iPhone
Simulator/3.1.3/Applications/8650FFE4-9C18-425C-9CEE-7392FD788E6D/Documents/temp/test.zip.download'
to '/Users/admin/Library/Application Support/iPhone
Simulator/3.1.3/Applications/8650FFE4-9C18-425C-9CEE-7392FD788E6D/Documents/test.zip'
can any body tell mw this error what wrong in my code......
NSURL *url = [NSURL URLWithString:#"http://wordpress.org/latest.zip"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/test.zip", [dirArray objectAtIndex:0]];
//NSString *tempPath = [NSString stringWithFormat:#"%#test.zip", NSTemporaryDirectory()] ;
NSString *tempPath =[NSString stringWithFormat:#"%#/temp/test.zip.download", [dirArray objectAtIndex:0]];
// The full file will be moved here if and when the request completes successfully
[request setDownloadDestinationPath:path];
[request setTemporaryFileDownloadPath:tempPath];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[[self queue] addOperation:request]; //queue is an NSOperationQueue
do you already have a temp.zip in that location ?
It also happens if you didn't set the destination path correctly, using this method setDownloadDestinationPath: of ASIHTTPRequest...
Your call
[request setTemporaryFileDownloadPath:tempPath];
is not necessary, and is more than likely the source of your error.