How to upload an image to .ashx url in ios - iphone

I have searched a lot on google as well as on stackoverflow but did not get any satisfactory solution which works for me.
I have to upload an image on some particular url which is ending with extension .ashx.
I have seen how to upload on php server but here i am not getting any clue.
Please help me by providing some sample code.

As per my understanding aspx is the page and the .ashx is the code file which response back the output, in string format and .ashx file is a web handler. A web handler file works just like an aspx file....
So we consider.ashx same as .aspx then this code should work for you(which is running for me for .aspx page). This is making request to .net server.
iOS
UIImage *img = [UIImage imageNamed:#"test.png"];
NSData *imageData = UIImageJPEGRepresentation ( img , 90 );
NSString *urlString =#"www.xyz.com/ImageUpload.aspx?filename=test";
NSLog(#"IMAGE_UPLOAD_URL -------------> %#",urlString);
NSMutableURLRequest *request = [[[ NSMutableURLRequest alloc ] init ] autorelease ];
[request setURL :[ NSURL URLWithString :urlString]];
[request setHTTPMethod : #"POST" ];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [ NSString stringWithFormat : #"multipart/form-data; boundary=%#" ,boundary];
[request addValue :contentType forHTTPHeaderField : #"Content-Type" ];
/*  body of the post */
NSMutableData *body = [ NSMutableData data ];
[body appendData :[ NSData dataWithData :imageData]];
[request setHTTPBody :body];
NSData *returnData = [ NSURLConnection sendSynchronousRequest :request returningResponse : nil error : nil ];
NSString *returnString = [[ NSString alloc ] initWithData :returnData encoding : NSUTF8StringEncoding ];
InfoLog(#"_______ IMAGE_UPLOAD response -------------> .%#.",returnString);
.NET
Retrieving image like this for .aspx page
if (Request.QueryString["filename"] != null)
{
string filename = Request.QueryString["filename"].ToString();
string saveFilePath = ConfigurationManager.AppSettings["CPSBImageFolder"].ToString();
//string saveFilePath = Server.MapPath("~/images");
saveFilePath = saveFilePath + filename;
Stream objStream = Request.InputStream;
StreamReader objStreamReader = new StreamReader(objStream);
Image image = Image.FromStream(objStreamReader.BaseStream, true);
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
EncoderParameters param = new EncoderParameters(1);
param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
image.Save(saveFilePath, info[1], param);
Response.Write("true");
}
Not sure but hope this give you a clue.

Verify that the variable(NSData) you are using to upload image is not null & your dot net server is receiving request.

Related

Base64 encoded image corrupted during transfer to server

For some reason i can't upload a jpeg file to a server using the post method in NSURLRequest
I have an android app that uses the same php code and can upload and download images fine by converting the image to a byte array and then using base64 encoding to send and receive.
My iPhone app downloads the image fine, The php script encodes using base64 and i use a base64 decoder in my iPhone app which I then convert into an image. This works fine.
However the uploading of the image doesn't work.
I convert the image to a base64 encoded string (I've used a few different methods for the base64 encoding and they all give the same result) then I post to the server, decode on the server side and save to file on the server.
The resulting decoded file on the server is a corrupt jpeg image. The corrupt file size is 3 times as many bytes as it should be.
The base64 encoded string generated for the upload is also very different to the base64 encoded string generated when downloading the same jpeg file from the server (ie. the valid image file that I uploaded using an ftp service).
My code is shown below along with the php script to receive the image.
I believe there is something happening with escaping characters which is causing the base64 string to become corrupted during the transfer but can't work it out.
Why is my base64 string being corrupted during transfer?
NSString* comments = #"comments to go with image";
NSData *data = UIImageJPEGRepresentation(_imageView.image, 1);
NSString *base64EncodedImage = [NSString base64StringFromData: data length: data.length];
//load the team posts so we know what items have been posted and what haven't
NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
comments, #"comment",
base64EncodedImage , #"image",
nil];
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in postDict) {
NSString *part = [NSString stringWithFormat: #"%#=%#", key, [postDict objectForKey:key]];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
NSData *postData = [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
NSString* url = #"http://www.scroppohunt.com/upload.php";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
_data = [[NSMutableData data] init];
}
and the php script that receives the image
<?php
$comments = $_REQUEST['comment'];
//do some database stuff with the comments
////////////////////////////////////////
//save the file to the images folder
///////////////////////////////////////////
$base=$_REQUEST['image'];
if(strlen($base) > 0)
{
// base64 encoded utf-8 string
$binary=base64_decode($base);
$file = fopen("postImages/test.jpg", 'wb');
fwrite($file, $binary);
fclose($file);
}
//display the bae64 encoded string taht was uploaded
echo $base;
?>
Well, it's been a while when you asked this question, but if anyone (like me) find this question, this may help:
In your Base64 encoded image, you should replace all occurrences of "+" character, with "%" character. Translated into code, it would be:
NSString* encodedImageString = [base64EncodedImage stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
Then, instead of adding base64EncodedImage in postDict, you should add encodedImageString.
That way, your postDict will look like this:
NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
comments, #"comment",
encodedImageString , #"image",
nil];
I think this will solve the problem, at least, was for me.
Cheers.
I also had this problem. For me, what was happening was that all the "+" were replaced with "space" after being sent to the server. There was no other such corruption:
Try Changing content type.
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];

iOS Unable to store URL contents into array

I have to connect to a URL to check whether the records is empty. The response looks something like this:
<?xml version = "1.0" encoding = "UTF-8"?>
<find>
<record_id>1234</record_id>
<no_record>00001</no_record>
<entry_num>00001</entry_num>
<session-id>aijheifaohqrihelrkqn324tlejaofjaf</session-id>
</find>
My codes:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]
autorelease];
[request setURL:[NSURL URLWithString: finalSearchURL]];
// Content-Type related.
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
// Create Connection.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
// The connection was established.
NSMutableData *receivedData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:request]];
NSLog( #"Data will be received from URL: %#", request.URL );
NSLog(#"Recieved Data 2: %#", receivedData);
}
else
{
// The download could not be made.
NSLog( #"Data could not be received from: %#", request.URL );
}
But it returns me:
Recieved Data : <3c3f786d 6c207665 7273696f 6e203d20 22312e30 2220656e 636f6469 6e67203d 20225554 462d3822 3f3e0a3c 66696e64 3e0a3c73 65745f6e 756d6265 723e3031 39303633 3c2f7365 745f6e75 6d626572 3e0a3c6e 6f5f7265 636f7264 733e3030 30303030 3030313c 2f6e6f5f 7265636f 7264733e 0a3c6e6f 5f656e74 72696573 3e303030 30303030 30313c2f 6e6f5f65 6e747269 65733e0a 3c736573 73696f6e 2d69643e 4d505843 33323433 58564336 4534454a 41464232 45473541 39374237 584e3832 43554631 4e314234 584e4c37 424c5947 4e533c2f 73657373 696f6e2d 69643e0a 3c2f6669 6e643e0a 20>
Can anyone help to tell me what am I doing wrong? This is my first attempt for getting response from a url please help thanks!
See the data as a string this way:
NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"the xml string is %#", string);
If the parsing goal is simple enough - like just to find the value of one tag - you can use string methods to parse. Otherwise, NSXMLParser or several other options are available.
To see if the string contains a substring, you can do something like this:
if (string) {
NSRange range = [string rangeOfString:#"<session-id>"];
if (range.location != NSNotFound) {
// session-id tag is at index range.location, so we know it's there
}
}
The method you used is to get the raw data from the url. You need a parser to convert the raw data to the understandable structure (probably NSDictionary rather than NSArray).
Apple has provided NSXMLParser for you to retrieve the xml structure from the url or you can find other xml parser libraries.
Actually, your code is returning the correct data. Since NSData can hold any kind of data, it will just display the hex value. If you convert the hex data to a sting, you'll see that it has the correct text.
Now, your code can be simplified a lot. All the code for setting up the NSURLConnection is not needed at all. All you need is the following line.
NSString *recievedText = [NSString stringWithContentsOfFile:finalSearchURL encoding:NSUTF8StringEncoding error:NULL];

http GET on iOs

Im trying to get answer (an image) from a service on a PC with a HTTP GET request.
If I put the request into a webbrowser, I get the requested image. If I try to get it in iPhone app, it doesnt work.
the request is:
http://192.168.151.82:54000/snapshot?s=<snapshotrequest xmlns=\"http://www.vizrt.com/snapshotrequest\"><videomoderequest><width>880</width><height>495</height></videomoderequest><snapshotdata view=\"all\"/></snapshotrequest>&p=http://192.168.151.82:8580/element_collection/storage/shows/%%257B3646FFAC-4E77-41AB-BDFC-F581D157ABA3%%257D/elements/1000/
my code for getting is:
NSString *str = [NSString stringWithFormat: #"http://192.168.151.82:54000/snapshot?s=<snapshotrequest xmlns=\"http://www.vizrt.com/snapshotrequest\"><videomoderequest><width>880</width><height>495</height></videomoderequest><snapshotdata view=\"all\"/></snapshotrequest>&p=http://192.168.151.82:8580/element_collection/storage/shows/%%257B3646FFAC-4E77-41AB-BDFC-F581D157ABA3%%257D/elements/1000/"];
NSURL *url = [[NSURL alloc] initWithString:str];
UIImage *img = [ [ UIImage alloc ] initWithData: [ NSData dataWithContentsOfURL: url ] ];
You can see, that speciel characters like quotes and percentes are handeled.
Im watching network communication on the PC with wireshark and there isn't any communication.
You need to url encode your parameters before creating a url from them
NSString * unencodeParameter = #"<snapshotrequest xmlns=\"http://www.vizrt.com/snapshotrequest\"><videomoderequest><width>880</width><height>495</height></videomoderequest><snapshotdata view=\"all\"/></snapshotrequest>&p=http://192.168.151.82:8580/element_collection/storage/shows/%%257B3646FFAC-4E77-41AB-BDFC-F581D157ABA3%%257D/elements/1000/";
NSString * encodedParameter = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedParameter,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );
NSString *str = [NSString stringWithFormat: #"http://192.168.151.82:54000/snapshot?s=%#",encodedParameter];
NSURL *url = [[NSURL alloc] initWithString:str];
UIImage *img = [ [ UIImage alloc ] initWithData: [ NSData dataWithContentsOfURL: url ] ];
And also make sure your iPhone is on same wifi as your computer as you are using local IP address

How do I download a file from S3 to an iPhone application?

I am new to iPhone development. I am developing an iPhone application which needs to open files stored on Amazon's S3 service.
How do I download a file from S3 to my iPhone application? I have tried Amazon's SDK, but they don't seem to provide a means of downloading and saving a file. How do I go about obtaining a file's URL from S3 and saving it in my application?
I always use the ASIHttpRequest library to do this and it's quite simple, here's a sample code from their website:
NSString *secretAccessKey = #"my-secret-access-key";
NSString *accessKey = #"my-access-key";
NSString *bucket = #"my-bucket";
NSString *path = #"path/to/the/object";
ASIS3ObjectRequest *request = [ASIS3ObjectRequest requestWithBucket:bucket key:path];
[request setSecretAccessKey:secretAccessKey];
[request setAccessKey:accessKey];
[request startSynchronous];
if (![request error]) {
NSData *data = [request responseData];
} else {
NSLog(#"%#",[[request error] localizedDescription]);
}
You can't get easier than this :)
If you don't have the luxury of simplicity using ASI, and/or are stuck with AWSiOS SDK, it's not a lot different:
/* borrowed from Maurício Linhares's answer */
NSString *secretAccessKey = #"my-secret-access-key";
NSString *accessKey = #"my-access-key";
NSString *bucket = #"my-bucket";
NSString *path = #"path/to/the/object";
/********************************************/
AmazonCredentials *credentials = [[AmazonCredentials alloc] initWithAccessKey: accessKey withSecretKey: secretAccessKey];
AmazonS3Client *connection = [[AmazonS3Client alloc] initWithCredentials: credentials];
S3GetObjectRequest *downloadRequest = [[[S3GetObjectRequest alloc] initWithKey:path withBucket: bucket] autorelease];
[downloadRequest setDelegate: self]; /* only needed for delegate (see below) */
S3GetObjectResponse *downloadResponse = [self.awsConnection getObject: downloadRequest];
Then you can look at downloadResponse.body and downloadResponse.httpStatusCode, preferable in a delegate:
-(void)request: (S3Request *)request didCompleteWithResponse: (S3Response *) response {
NSLog(#"Download finished (%d)",response.httpStatusCode);
/* do something with response.body and response.httpStatusCode */
/* if you have multiple requests, you can check request arg */
}

iphone SDK:How use URL to post data back?

I read a plist data at LightTableViewController.m
and I load a data like this :
LOG RESULT:
The Plist Data Is : (
{
category = 11;
id = 1;
name = "LIVING RM";
status = 0;
},
{
category = 11;
id = 2;
name = "BEDROOM RM";
status = 0;
}
)
I need to post the "id" and "status" back to the database
to control which light to turn on or turn off
And this part is the my post method,It's in LightCell0.m
- (void)switchToggled:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender;
UITableViewCell *cell = (UITableViewCell *)theSwitch.superview.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
if(theSwitch.on) {
NSURL * url;
NSMutableURLRequest * request;
NSString *_urlString = #"http://10.85.28.99/req_light.php";
url = [self smartURLForString:_urlString];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//This is my first post method,it is static,only get the indexPath,Not a real id and status I want to post back
NSString *post = [NSString stringWithFormat:#"lightcb%i=1", indexPath.row+1];
NSData *postData = [ NSData dataWithBytes: [ post UTF8String ] length: [ post length ] ];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
else {
NSURL * url;
NSMutableURLRequest * request;
NSString *_urlString = #"http://10.85.28.99/req_light.php";
url = [self smartURLForString:_urlString];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//I got one error and one warring
//Error is "Request for member 'plist' in something not a structure or union"
//Warning is 'NSString' may not resopnd to '+stringWithFormat:value=ForKey'
NSString *post = [ NSString stringWithFormat:#"id=%i,status=0",
[[self.plist objectAtIndex:indexPath.row] valueForKey:#"id"]];
NSData *postData = [ NSData dataWithBytes: [ post UTF8String ] length: [ post length ] ];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
}
So...my question is
<1>How to post two data back (is it right to use "," to separated two return variables ?
<2>How to eliminate the error "Request for member 'plist' in something not a structure or union"
Great Thanks
1) POST values are separated by '&' like GET values in an URL.
2) The 'Request for member'... line tells you that your member does not exist, or at least is not declared in this scope, the warning 'NSString may not respond...' tells you you're trying to invoke a message/method on NSString which should be invoked on another class (NSDictionary would be my guess here).