Somebody please... #$%^ please take a look at this. days walking through the debugger, using setData with a jpeg representation. set file using ios4 asset library, trying a new PHP script, deleting the asiHTTPrequest files and making damn sure I have the new ones. Still nothing... Half the code has been put together from examples here or elsewhere on the web.
The goal here, is to simply pick a photo from the camera roll, and upload it, seems pretty easy, I had a different PHP script that was working fine from the desktop and nabbed one from here because it's much more concise and it works from the desktop as well.
so the override for finishing image picking
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// dealing with a still image
if(CFStringCompare((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo){
editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
originalImage = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage];
/*
if(editedImage){
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}
*/
chosenImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
//_imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(originalImage, 0.0)];
//_imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(chosenImage.image, 0.0)];
UIImage *im = [info objectForKey:#"UIImagePickerControllerOriginalImage"] ;
UIGraphicsBeginImageContext(CGSizeMake(320,480));
[im drawInRect:CGRectMake(0, 0,320,480)];
_resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(_resizedImage, 0.0)];
}
[picker release];
}
then the upload method.
-(void)uploadPhoto
{
//NSLog(#"image path inside uploadPhoto --> %#", _imagePath);
NSLog(#"uploadPhoto");
//NSLog(#"%#", imageData);
//_imageData = _imageData;
NSString *unescapedURL = #"http://dev.xxxx.com/upload.php";
NSString * escapedURL =
(NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unescapedURL,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:unescapedURL];
//NSURL *url = [NSURL URLWithString:unescapedURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
//[request setStringEncoding:NSUTF8StringEncoding];
//[request addPostValue:#"submit" forKey:#"Submit"];
//[request setPostValue:#"Submit" forKey:#"Submit"];
[request setData:_imageData withFileName:#"image4.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
//[request setFile:_imagePath forKey:#"photo"];
//[request setFile:_imagePath withFileName:#"image5.png" andContentType:#"image/png" forKey:#"photo"];
[request setDidFailSelector:#selector(requestFailed:)];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setTimeOutSeconds:500];
[request startAsynchronous];
NSError *error = nil;
NSString *theString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
if( theString )
{
NSLog(#"Text=%#", theString);
}
else
{
NSLog(#"Error = %#", error);
NSString *localized = [error localizedDescription];
NSString *localizedFail = [error localizedFailureReason] ? [error localizedFailureReason] : NSLocalizedString(#"not it", nil);
NSLog(#"localized error--> %#", localized);
NSLog(#"localizedFail--> %#", localizedFail);
}
[escapedURL release];
}
then the finish/fail selectors
-(void)requestFinished:(ASIFormDataRequest *)request
{
NSLog(#"requestFinished");
NSString *respondingString = [request responseString];
NSLog(#"response string--> %#", respondingString);
NSData *responseData = [request responseData];
NSLog(#"%#", responseData);
}
-(void)requestFailed:(ASIFormDataRequest *)request
{
NSLog(#"requestFailed");
//NSError *error = [request error];
//NSLog(#"%#", [error description]);
}
Help! Drowning...
It was a problem with the PHP.
move_uploaded_file($_FILES["file"]["tmp_name"]
was the issue.
if you look at this
[request setData:_imageData withFileName:#"image4.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
It's changing the POST so the standard...
move_uploaded_file($_FILES["file"]["tmp_name"]
needs to be
move_uploaded_file($_FILES["photo"]["tmp_name"]
adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
print_r($_FILES);
to the PHP allowed me to see..
response string--> Array
(
[photo] => Array
(
[name] => image4.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpCSXJgl
[error] => 0
[size] => 150854
)
)
in the selector defined by...
[request setDidFinishSelector:#selector(requestFinished:)];
What I'll do from here is revert the PHP to where it was before
move_uploaded_file($_FILES["file"]["tmp_name"]
and change the setFile call to
[request setData:_imageData withFileName:#"image4.jpg" andContentType:#"image/jpeg" forKey:#"file"];
all will be well with the world and I'm going to get some food. cheers!
Related
Hi I just used image picker view to record a video and convert the video formate mov to mp4 and change NSData for posting. But it is not working I get 415 error some times 500 errors. Please check below code for how I implemented. Anybody can guid or help me for this issue.
if I need to check my server side team , they test with postman it is working well when I am implement of below code it is not working if may did any mistakes please guid me thank you
-(void)camerabuttonHandlerqas{
UIAlertController * picker = [UIAlertController alertControllerWithTitle:#"Pick an image using" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { }];
UIAlertAction* takeVideo = [UIAlertAction actionWithTitle:#"TakeVideo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
imagePicker.view.tag = 100;
[self presentViewController:imagePicker animated:YES completion:nil]; }];
[picker addAction:picture];
[picker addAction:cancel];
picker.view.tintColor = [UIColor grayColor];
[self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - <UIImagePickerControllerDelegate>
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
videoURL = info[UIImagePickerControllerMediaURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* videoPath = [NSString stringWithFormat:#"%#/test_%d.mp4", [paths objectAtIndex:0],arc4random_uniform(1000)];
NSURL *outputURL = [NSURL fileURLWithPath:videoPath];
[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusFailed:
NSLog(#"status failed");
break;
case AVAssetExportSessionStatusCompleted:{
NSLog(#"status success %# ",videoPath);
NSMutableDictionary *data = [NSMutableDictionary new];
videoURL = info[UIImagePickerControllerMediaURL];
[data setObject:[self generatePostDataForData:[NSData dataWithContentsOfFile:videoPath]] forKey:#"SelectedvideoURL"];
imagePickerIsSelected = YES;
[self postData:data];
break;
}
}];
[picker dismissViewControllerAnimated:YES completion:nil]; }
- (NSData *)generatePostDataForData:(NSData *)uploadData
{ // Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\";
filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength: [postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
-(void) postData:(NSData *)data
{
service = [NSString stringWithFormat:#"http://1.1.1.1:8080/testing/postapi/photoUpload/uploadVideo?videoName=video_%d&type=mp4",arc4random_uniform(1000)]
delegate = delegateInstance;
service = [service stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLFragmentAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:service]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
[request setValue:#"mp4/MOV" forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// add image data
if (videoData) {
[body appendData:videoData];
}
// setting the body of the post to the reqeust
[request setHTTPBody:videoData];
// set URL
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
} }]; [dataTask resume]; }
415 error media type error check your server data type on which u r storing NSDATA.
I got solution that code is absolutely right and no need to change media type to mp4 if server side accept .mov type and please discuss with server side then have to change content type, and take file like as a one data then its working for me
Thank you.
I need to add an upload video feature to my iOS app. That said, I am using a WCF service but it seems that is not working, the file is uploaded but the video is trowing an error.
This is my code from my IOS app:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.movie"]){
NSLog(#"got a movie");
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *data = [NSData dataWithContentsOfFile:videoURL];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://dotstudioservices.com/labajaService/Service1.svc/videoempresa"]];
[request addValue:#"video" forHTTPHeaderField: #"Content-Type"];
[request setHTTPMethod:#"POST"];
NSInputStream *inputStream = [[NSInputStream alloc] initWithFileAtPath:[videoURL path]];
[request setHTTPBodyStream:inputStream];
[NSURLConnection
sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error)
{
if ([data length] >0 && error == nil)
{
NSLog(#"Request ended");
}
else if ([data length] == 0 && error == nil)
{
NSLog(#"Nothing was downloaded.");
}
else if (error != nil){
NSLog(#"Error = %#", error);
}
}];
}
[picker dismissViewControllerAnimated:YES completion:NULL]; }
And this is my code of the WCF service:
public Status FileUploadVideo(Stream stream)
{
byte[] buffer = new byte[1000000];
stream.Read(buffer, 0, 1000000);
FileStream f = new FileStream("D:\\Hosting\\9692238\\html\\promosbc\\videoslabaja\\video.mp4", FileMode.OpenOrCreate);
f.Write(buffer, 0, buffer.Length);
f.Close();
stream.Close();
return new Status { status = "done" };
}
i have a form that contains some person information and an image. i tried to save information in post using this function and it work well :
- (void)Inscription:(NSArray *)value completion:(void (^)( NSString * retour))block{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSArray *Param_header = #[#"username", #"password", #"email",#"first_name", #"last_name",#"image"];
// NSArray *Param_value = #[#"ali", #"aliiiiiiii", #"ali.ali#gmail.com",#"ali",#"zzzzz"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: [NSString stringWithFormat:#"http:// /Messenger/services/messenger_register"]]];
NSString *aa=[self buildParameterWithPostType:#"User" andParameterHeaders:Param_header ansParameterValues:value];
[request setHTTPBody:[aa dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
NSError *error = Nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block([NSString stringWithFormat:#"%#", [jsonObjects objectForKey:#"message"]]);
}
}
];
}
No, i want to send the photo taked, i convert it to NSData first :
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *imag= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imag = [imag scaleAndRotateImage:imag];
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 25*1024;//was 250x1024
NSData *imageData = UIImageJPEGRepresentation(imag, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imag, compression);
}
NSData _D_ImageData = imageData;
And i tried to do this to send it to server but image c'ant be uploaded:
[web Inscription:Param_value completion:^(NSString *retour) {
CustomPrpgress.hidden=true;
NSLog(#" eee %# ",retour);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:retour message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}];
Can someone help me, i'm beginner and this is my first time. thank you
My code work fine, i made a mistake in the php file
How to upload a image to server using ASIFormDataRequest ?
i tried to upload a image its does't show's any error while inserting. and in my requesting did finished method iam getting response as success. so what is the problem is, when i get the data what i have inserted in that i am not able to get the image what i have inserted but iam getting the image path also.
here is my code
NSString *globalurl =[[NSUserDefaults standardUserDefaults]valueForKey:#"Global_Url"];
NSString *urlStr=[NSString stringWithFormat:#"%#/InsertUserInfo?User_Name=%#&User_Pwd=%#&User_FName=%#&User_LName=%#&User_Mail=%#&User_Phno=%#&User_Address=%#&User_Dob=%#&Ic_No=%#&User_Active=%#&User_Questions=%#&User_Ans=%#",globalurl,usernameTxtFld.text,pwdTxtFld.text,firstName.text,lastName.text,email.text,phonNO.text,address.text,dateOfbirth.text,nricNo.text,#"10001",#"",#""];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request addData:dataImage withFileName:#"Image.png" andContentType:#"image/png" forKey:#"photo"];
//check if passedData is nil
if (dataImage == nil)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"title:iDnil" message:#"nil" delegate:nil cancelButtonTitle:#"fgff" otherButtonTitles:#"erer", nil];
[alert show];
}
[request startAsynchronous];
-(void)requestFinished:(ASIHTTPRequest *)request {
NSString *receivedString = [request responseString];
NSLog(#"received messge %#",receivedString);
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Message" message:receivedString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
NSLog(#"dict is %#",info);
UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissModalViewControllerAnimated:YES];
}
You can use
[request setFile:#"YOUR IMAGE FILE PATH" forKey:#"photo"];
instead of [request addData:dataImage withFileName:#"Image.png" andContentType:#"image/png" forKey:#"photo"];
as explained in the post . It worked for me like a charm :-)
I have uploaded an example application performing textfile, Image, Video, Images upload in queue, Videos to GitHub on this link. You may well consider having a look at it.
ASI-http-request has an optimisation option to stream your image files right away from your disk, which is the best I've seen with this library. Please consider using the below code snippet for creating ASIFormDataRequest.
// Initilize Variables
NSURL * url = [NSURL URLWithString:IMAGE_POST_URL];
// Add Image
NSString *path = [[NSBundle mainBundle]pathForResource:#"image1" ofType:#"jpg"];
// Get Image
NSData *imageData = [[NSData alloc]
initWithContentsOfFile:path];
// Return if there is no image
if(imageData != nil){
//Request-1
ASIFormDataRequest * request1;
[request1 setTag:201];
request1 = [[ASIFormDataRequest alloc] initWithURL:url];
[request1 setPostValue:#"ID = 201" forKey:#"image_upload"];
[request1 setFile:path forKey:#"image1_file"];
[request1 setDelegate:self];
[request1 setDidFinishSelector:#selector(imageUploadDidFinish:)];
[request1 setDidFailSelector:#selector(imageUploadDidFail:)];
[request1 setTimeOutSeconds:500];
[request1 setShouldStreamPostDataFromDisk:YES];
}
I am uploading multiple images to server using ASIHTTPRequest.
-(void)uploadImagesToServer
{
[[self networkQueue] cancelAllOperations];
// Creating a new queue each time we use it means we don't have to worry about clearing delegates or resetting progress tracking
[self setNetworkQueue:[ASINetworkQueue queue]];
[[self networkQueue] setDelegate:self];
[[self networkQueue] setRequestDidStartSelector:#selector(uploadRequestStarted:)];
[[self networkQueue] setRequestDidFinishSelector:#selector(requestFinished:)];
[[self networkQueue] setRequestDidFailSelector:#selector(requestFailed:)];
[[self networkQueue] setQueueDidFinishSelector:#selector(queueFinished:)];
[[self networkQueue] setUploadProgressDelegate:self.uploadBar];
[[self networkQueue] setShowAccurateProgress:YES];
[ASIHTTPRequest setDefaultTimeOutSeconds:30];
for (int i = 0; i< appDelegate.selImageDetails.count; i++) {
NSMutableDictionary *dic = [appDelegate.selImageDetails objectAtIndex:i];
NSString *orderid = [[NSUserDefaults standardUserDefaults] objectForKey:#"orderId"];
if ([[dic objectForKey:#"Status"] isEqualToString:#"N"] || [[dic objectForKey:#"Status"] isEqualToString:#"Failed"])
{
NSURL *url = [NSURL URLWithString:#"http://180.151.100.53:9776/App_Frame_IT/UploadImage"];
NSLog(#"UPLOAD IMAGE ARRAY == %#",dic);
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:orderid forKey:#"OrderId"];
[request addPostValue:[dic objectForKey:#"ImageName"] forKey:#"imgName"];
[request addPostValue:#"10" forKey:#"appId"];
[request addPostValue:[dic objectForKey:#"Frame"] forKey:#"frameSize"];
[request addPostValue:[dic objectForKey:#"Quantity"] forKey:#"Quantity"];
NSString *imgCount = [NSString stringWithFormat:#"%d", [appDelegate.selImageDetails count]];
[request addPostValue:imgCount forKey:#"totalimages"];
[request addPostValue:[dic objectForKey:#"paperQuality"] forKey:#"paper_quality"];
NSURL *assetURL = [dic objectForKey:#"assetPathURL"];
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want
//NSLog(#"returned Image ====> %#", data);
// UIImageView *testImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 10, 50, 50)];
NSLog(#"FUll REsolution Image Size in MB = %.2f",(float)data.length/1024.0f/1024.0f);
//[data writeToFile:photoFile atomically:YES];//you can save image later
//NSData *imageData = [[NSData alloc] initWithContentsOfMappedFile:[dic objectForKey:#"Path"]];
[request addData:data withFileName:[dic objectForKey:#"ImageName"] andContentType:#"image/png" forKey:#"uploadfile"];
//[data release];
NSLog(#"requestGenrated table count---%d ",[appDelegate.selImageDetails count]);
NSString *requestUserName = [NSString stringWithFormat:#"upload%i",i];
[request setUsername:requestUserName];
[request setUserInfo:[NSDictionary dictionaryWithObject:[dic objectForKey:#"unique"] forKey:#"uniqueId"]];
[request setTag:i];
[request setShowAccurateProgress:YES];
[request setRequestMethod:#"POST"];
[request setShouldContinueWhenAppEntersBackground:YES];
[[self networkQueue] addOperation:request];
[dic setObject:#"Y" forKey:#"requestGenrated"];
[appDelegate.selImageDetails replaceObjectAtIndex:i withObject:dic];
NSLog(#"Upload Request Created");
} failureBlock:^(NSError *err) {
NSLog(#"Error: %#",[err localizedDescription]);
}];
[pool drain];
}
else
{
NSLog(#"((Image already uploaded))");
}
}
failedRequests = 0;
[networkQueue setShouldCancelAllRequestsOnFailure:YES];
[[self networkQueue] go];
}
I am getting these images from ALAssetsLibrary as you can see above in the code. I am able to upload all the images successfully but the problem is that, it is consuming too much memory (see screenshot)
I am not able to release this memory even after uploading all the images or moving to different view. What am I suppose to do, which object do I've to release?
Thanks
Set up the cachePolicy of NSURLRequest to avoid cache, should be similar in ASIFormDataRequest
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData