dongmi1995 2016-02-24 18:23
浏览 53

上传图片时出错

I have a problem uploading an image to my server, i have my code with which I connect to my server, I tried it and if it works locally to upload it to my server thunders that mistake will

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate, NSURLConnectionDelegate>{
IBOutlet UILabel *response;
NSMutableData *_responseData;
}
@property (strong, nonatomic) IBOutlet UIImageView* imageView;
- (IBAction) pickImage:(id)sender;
@end

ViewController.m

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController
{
    NSData *pngData;
    NSData *syncResData;
    NSMutableURLRequest *request;
    UIActivityIndicatorView *indicator;

    #define URL            @"http://localhost/UploadImage/Upload_Image.php"
    #define NO_CONNECTION  @"No Connection"
    #define NO_IMAGE      @"NO IMAGE SELECTED"
 }

 - (void)viewDidLoad {
    [super viewDidLoad];
    pngData = nil;
    [self initPB];
 }

 - (IBAction) pickImage:(id)sender{

    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
 }

 #pragma mark -
 #pragma mark UIImagePickerControllerDelegate

 - (void) imagePickerController:(UIImagePickerController *)picker
      didFinishPickingImage:(UIImage *)image
      editingInfo:(NSDictionary *)editingInfo
 {
     self.imageView.image = image;
     pngData = UIImagePNGRepresentation(image);
     [self dismissModalViewControllerAnimated:YES];
 }

 -(BOOL) setParams{

    if(pngData != nil){

       [indicator startAnimating]; 
       request = [NSMutableURLRequest new];
       request.timeoutInterval = 20.0;
       [request setURL:[NSURL URLWithString:URL]];
       [request setHTTPMethod:@"POST"];

        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:@"User-Agent"];

        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"
--%@
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"%@.png\"
", @"Uploaded_file"] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"Content-Type: application/octet-stream

" dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[NSData dataWithData:pngData]];

        [body appendData:[[NSString stringWithFormat:@"
--%@--
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        [request setHTTPBody:body];
        [request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];

        return TRUE;

    }else{

        response.text = NO_IMAGE;
        return FALSE;
    }
}

- (IBAction) uploadImageSync:(id)sender{

   if( [self setParams]){

       NSError *error = nil;
       NSURLResponse *responseStr = nil;
       syncResData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseStr error:&error];
       NSString *returnString = [[NSString alloc] initWithData:syncResData encoding:NSUTF8StringEncoding];

       NSLog(@"ERROR %@", error);
       NSLog(@"RES %@", responseStr);

       NSLog(@"%@", returnString);

         if(error == nil){
            response.text = returnString;
         }

       [indicator stopAnimating];

    }

}




-(void) initPB{
    indicator = [[UIActivityIndicatorView    alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width)/2, ([UIScreen mainScreen].bounds.size.height)/2 , 40.0, 40.0);
    indicator.center = self.view.center;
    [self.view addSubview:indicator];
    [indicator bringSubviewToFront:self.view];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}

 #pragma mark NSURLConnection Delegate Methods

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
     // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    // Append the new data to the instance variable you declared
     [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
              willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
     return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   // The request is complete and data has been received
   // You can parse the stuff in your instance variable now

    response.text = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    NSLog(@"_responseData %@", response.text);

    [indicator stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;  
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var

    NSLog(@"didFailWithError %@", error); 
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

With this code by the image smoothly on the local server, my code php is:

<?php
    $target_path1 = "fotosTaqueria/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1){
      echo "The file ".  basename( $_FILES['uploaded_file']['name']).
      " has been uploaded to ".$target_path1;;
   } else{
      echo "There was an error uploading the file, please try again!";
      echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
      echo "target_path: " .$target_path1;
   }
?>

I will have the problem that the server does not let me upload image Help me see my mistake ,Thanks for your time

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥120 计算机网络的新校区组网设计
    • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
    • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
    • ¥20 海浪数据 南海地区海况数据,波浪数据
    • ¥20 软件测试决策法疑问求解答
    • ¥15 win11 23H2删除推荐的项目,支持注册表等
    • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
    • ¥15 qt6.6.3 基于百度云的语音识别 不会改
    • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
    • ¥15 神经网络怎么把隐含层变量融合到损失函数中?