Table of Contents
1. 将图片转换为Base64编码,POST上传。PHP将Base64解码为二进制,再写出文件。缺点:不能上传较大的图片
2.AFNetworking上传,PHP端通过正常接收网页上传方法来接收图片
3.将图片封装在Http的请求报文中的请求体(body)中上传。也是AFN上传的原理
4.iOS图片转换为NSData,通过POST上传。PHP接收POST参数,将NSData的16进制编码转换为PHP支持的二进制,再写出文件保存
5.二进制POST上传。PHP直接将数据保存为图片
Home Backend Development PHP Tutorial iOS上传图像到服务器,以及服务器PHP接收的几种方法

iOS上传图像到服务器,以及服务器PHP接收的几种方法

Jun 23, 2016 pm 01:05 PM

1. 将图片转换为Base64编码,POST上传。PHP将Base64解码为二进制,再写出文件。缺点:不能上传较大的图片

// iOS(Swift)func upload(image: UIImage, url: String) {    let imageData = UIImageJPEGRepresentation(image, 0.3) // 将图片转换成jpeg格式的NSData,压缩到0.3    let imageStr = imageData?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) // 将图片转换为base64字符串    let params: NSDictionary = ["file": imageStr!]    let manager = AFHTTPRequestOperationManager()    // 采用POST的方式上传,因为POST对长度没有限制    manager.POST(url, parameters: params, success: { (_: AFHTTPRequestOperation!, response: AnyObject!) in        // 成功    }) { (_: AFHTTPRequestOperation!, _: NSError!) in        // 失败    }}
Copy after login
<?phpheader('Content-type: text/json; charset=UTF-8');$base64 = $_POST["file"]; // 得到参数$img = base64_decode($base64); // 将格式为base64的字符串解码$path = "md5(uniqid(rand()))".".jpg"; // 产生随机唯一的名字作为文件名file_put_contents($path, $img); // 将图片保存到相应位置?>
Copy after login

2.AFNetworking上传,PHP端通过正常接收网页上传方法来接收图片

static func uploadPortrait(image: UIImage, url: String) {    let manager = AFHTTPRequestOperationManager()    // fromData: AFN封装好的http header类,可以添加请求体    manager.POST(url, parameters: [:], constructingBodyWithBlock: { (fromData: AFMultipartFormData!) in        let pngData = UIImagePNGRepresentation(image)        // name必须和后台PHP接收的参数名相同($_FILES["file"])        // fileName为图片名        fromData.appendPartWithFileData(pngData, name: "file", fileName: "image.png", mimeType: "image/png")              // let jpegData = UIImageJPEGRepresentation(image, 0.3)        // fromData.appendPartWithFileData(jpegData, name: "file", fileName: "image.jpg", mimeType: "image/jpeg")    }, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in        // 成功    }) { (operation: AFHTTPRequestOperation!, error: NSError!) in        // 失败    }   }
Copy after login
<?phpheader('Content-type: text/json; charset=UTF-8' );/** * $_FILES 文件上传变量,是一个二维数组,第一维保存上传的文件的数组,第二维保存文件的属性,包括类型、大小等 * 要实现上传文件,必须修改权限为加入可写 chmod -R 777 目标目录 */// 文件类型限制// "file"名字必须和iOS客户端上传的name一致if (($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/png")|| ($_FILES["file"]["type"] == "image/pjpeg"))// && ($_FILES["file"]["size"] < 20000)) // 小于20k{    if ($_FILES["file"]["error"] > 0) {        echo $_FILES["file"]["error"]; // 错误代码    } else {                   $fillname = $_FILES['file']['name']; // 得到文件全名        $dotArray = explode('.', $fillname); // 以.分割字符串,得到数组        $type = end($dotArray); // 得到最后一个元素:文件后缀        $path = "../portrait/".md5(uniqid(rand())).'.'.$type; // 产生随机唯一的名字        move_uploaded_file( // 从临时目录复制到目标目录          $_FILES["file"]["tmp_name"], // 存储在服务器的文件的临时副本的名称          $path);        echo "成功";    } } else {    echo "文件类型不正确";}?>
Copy after login

3.将图片封装在Http的请求报文中的请求体(body)中上传。也是AFN上传的原理

// 使用OC封装#import <UIKit/UIKit.h>@interface RequestPostUploadHelper : NSObject+ (NSMutableURLRequest *)uploadImage:(NSString*)url uploadImage:(UIImage *)uploadImage params:(NSMutableDictionary *)params;@end#import "RequestPostUploadHelper.h"@implementation RequestPostUploadHelper+ (NSMutableURLRequest *)uploadImage:(NSString*)url uploadImage:(UIImage *)uploadImage params:(NSMutableDictionary *)params {    [params setObject:uploadImage forKey:@"file"];    //分界线的标识符    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";    //根据url初始化request    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData                                                       timeoutInterval:10];    //分界线 --AaB03x    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];    //结束符 AaB03x--    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];    //要上传的图片    UIImage *image=[params objectForKey:@"file"];    //得到图片的data    NSData* data = UIImagePNGRepresentation(image);    //http body的字符串    NSMutableString *body=[[NSMutableString alloc]init];    //参数的集合的所有key的集合    NSArray *keys= [params allKeys];    //遍历keys    for(int i = 0; i < [keys count]; i++)    {        //得到当前key        NSString *key = [keys objectAtIndex:i];        //如果key不是file,说明value是字符类型,比如name:Boris        if(![key isEqualToString:@"file"])        {            //添加分界线,换行            [body appendFormat:@"%@\r\n",MPboundary];            //添加字段名称,换2行            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];            //添加字段的值            [body appendFormat:@"%@\r\n",[params objectForKey:key]];        }    }    ////添加分界线,换行    [body appendFormat:@"%@\r\n",MPboundary];    //声明file字段,文件名为image.png    [body appendFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\n"];    //声明上传文件的格式    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];    //声明结束符:--AaB03x--    NSString *end=[[NSString alloc] initWithFormat:@"\r\n%@",endMPboundary];    //声明myRequestData,用来放入http body    NSMutableData *myRequestData = [NSMutableData data];    //将body字符串转化为UTF8格式的二进制    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];    //将image的data加入    [myRequestData appendData:data];    //加入结束符--AaB03x--    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];    //设置HTTPHeader中Content-Type的值    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];    //设置HTTPHeader    [request setValue:content forHTTPHeaderField:@"Content-Type"];    //设置Content-Length    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];    //设置http body    [request setHTTPBody:myRequestData];    //http method    [request setHTTPMethod:@"POST"];    return request;}@end
Copy after login
// 使用// Swiftstatic func uploadPortrait(image: UIImage, url:String) {    // 使用    let request = RequestPostUploadHelper.uploadImage(url, uploadImage: image, params: [:])    // 异步网络请求    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in        if error != nil {            // 失败        } else {            // 成功        }    }}
Copy after login
<?php// PHP代码和上一步相同?>
Copy after login

4.iOS图片转换为NSData,通过POST上传。PHP接收POST参数,将NSData的16进制编码转换为PHP支持的二进制,再写出文件保存

暂时没有找到办法,PHP接收到16进制编码后,使用算法转换为二进制后无法输出图片

5.二进制POST上传。PHP直接将数据保存为图片

暂时没有找到办法,iOS端使用NSData的getBytes无法转换为二进制

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles