简体   繁体   English

使用ios上传图片到php

[英]Uploading Images using ios to php

The images I try to upload from my Iphone gallery are all saved as ipodfile.jpg我尝试从我的 Iphone 图库上传的图片都保存为ipodfile.jpg

I want the exact image name which I am selecting from the gallery and I want to create a folder (with the login username) and I want to store inside the folder我想要我从图库中选择的确切图像名称,我想创建一个文件夹(使用登录用户名)并且我想存储在该文件夹中

For example例如

  • Username : Mike用户名:迈克
  • Image : welcome.jpg图片:欢迎.jpg

Then I want to create a folder named mike and save the image inside.然后我想创建一个名为mike的文件夹并将图像保存在里面。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    [self dismissModalViewControllerAnimated:true];

    img = [info valueForKey:UIImagePickerControllerOriginalImage];
    //images.image = img; 
    NSData *imageData = UIImageJPEGRepresentation(img, 90);
    NSString *urlString = @"http://192.168.1.92/Abdul/IOS/Chat/upload_file.php";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [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"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"Successfully uploaded");

}

This is the server-side code I'm using这是我正在使用的服务器端代码

<?php
$oname=$_FILES["file"]["name"];
$tempname=$_FILES["file"]["tmp_name"];
$path="upload";

echo "Upload: " . $oname . "<br />";
echo "Temp file: " . $tempname . "<br />";


echo "<br>";
$ex=file_exists("upload/$oname");

if($ex)
{
    echo "File Already exist";
}
else
{
    $upload=move_uploaded_file($tempname,$path.$oname);

    if($upload)
    {
        echo "Sucessfully Stored in: " . $path. $oname;
    }
    else
    {
    echo "Not stored Sucessfully : " . $path.$oname;
    }
}

You should take unique file name for every image like timestamp which will always be unique.您应该为每个图像取唯一的文件名,例如时间戳,这将始终是唯一的。

in below line you are setting image name so set it with time stamp.在下面的行中,您正在设置图像名称,因此请使用时间戳对其进行设置。

 [body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"ipodfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

You can kepp unique name aomething like this which i have used once,您可以保留我曾经使用过的这样的唯一名称,

            NSDate *currentDate = [[NSDate alloc] init];
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
            NSString *localDateString = [dateFormatter stringFromDate:currentDate];
            NSString* cleanedString = [[localDateString stringByReplacingOccurrencesOfString:@"." withString:@""]stringByReplacingOccurrencesOfString:@":" withString:@""];
            NSString *cleanedString2 = [cleanedString stringByAppendingFormat:@"%d",i];
            NSString *finalUniqueImageNAme = [cleanedString2 stringByAppendingString:@".jpg"];

Hope this will help ;)希望这会有所帮助;)

Update :更新 :

you can use unique name like this,您可以使用这样的唯一名称,

[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];

And second thing you should use AFNetworking to do this kind of stuff.第二件事你应该使用AFNetworking来做这种事情。 it'll manage all this kind of stuff like set boundary etc. Click here for AFNetworking github它将管理所有这些东西,如设置边界等。单击此处获取 AFNetworking github

Update 2 (according to query of comment):更新2(根据评论查询):

You should use NSURLSession instead of nsurlconnection because connection is deprecated now so your code should be like this你应该使用NSURLSession而不是nsurlconnection因为现在不推荐使用连接所以你的代码应该是这样的

 NSURLSession *session = [NSURLSession sharedSession];


[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    if (data) {

        //if response is in string format
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

        //if response in json format then
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    }



}]resume];

changes the path to将路径更改为

$path="mike/"; and then upload image.然后上传图片。 By this way your image will be uploaded in mike folder.通过这种方式,您的图像将上传到 mike 文件夹中。

    NSData *imageData = UIImagePNGRepresentation(yourImage);

    NSString *urlString = [ NSString stringWithFormat:@"http://192.168.1.92/Abdul/IOS/Chat/upload_file.php"];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [[body appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",img] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM