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

php中文网
发布: 2016-06-23 13:05:36
原创
1613人浏览过

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        // 失败    }}
登录后复制
<?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); // 将图片保存到相应位置?>
登录后复制

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        // 失败    }   }
登录后复制
<?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 "文件类型不正确";}?>
登录后复制

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
登录后复制
// 使用// 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 {            // 成功        }    }}
登录后复制
<?php// php代码和上一步相同?>
登录后复制

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

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

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

暂时没有找到办法,ios端使用nsdata的getbytes无法转换为二进制

火山方舟
火山方舟

火山引擎一站式大模型服务平台,已接入满血版DeepSeek

火山方舟 99
查看详情 火山方舟
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号