objective-c - Thinkphp+IOS上傳圖片該怎麼處理接收和數據
剛開始接觸APP端程序處理。
現在問題就卡在TP端接收IOS傳過來的圖片,請問TP端處理上傳的圖片資料該是如何流程?要注意些什麼問題,例如資料格式應該是什麼?
請問下面的處理方式正確嗎?
ios檔案如下:
XLSelectView.h檔案:
<code>// XLSelectView.h // XLUploadImages // Created by 薛林 on 16/6/18. // Copyright © 2016年 xuelin. All rights reserved. #import <UIKit/UIKit.h> @class ZLPhotoPickerViewController; @interface XLSelectView : UIView //跳转界面的block @property (nonatomic, copy) void(^presentVC)(ZLPhotoPickerViewController *pickerVC); //网络需要传入的参数 @property (nonatomic, copy) NSString *postUrlString; //parameters @property (nonatomic, strong) NSDictionary *parameters; //后台接收图片的字段 @property (nonatomic, copy) NSString *userfile; //加载xib + (instancetype)loadnib; @end </code>
XLSelectView.m檔:
<code>// XLSelectView.m // XLUploadImages // // Created by 薛林 on 16/6/18. // Copyright © 2016年 xuelin. All rights reserved. // #import "XLSelectView.h" #import "ZLPhoto.h" #import "AFNetworking.h" #import "DGGlobel.h" #import "DGSecret.h" @interface XLSelectView () //保存图片二进制数据 @property (nonatomic, strong) NSMutableDictionary *fileDict; @end @implementation XLSelectView #pragma mark - 懒加载字典 - (NSMutableDictionary *)fileDict { if (_fileDict == nil) { _fileDict = [NSMutableDictionary dictionary]; } return _fileDict; } #pragma mark - 加载xib + (instancetype)loadnib { return [[[NSBundle mainBundle]loadNibNamed:@"XLSelectView" owner:nil options:nil]lastObject]; } - (IBAction)selectMorePic:(id)sender { // 创建图片多选控制器 ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init]; // 默认显示相册里面的内容SavePhotos pickerVc.status = PickerViewShowStatusSavePhotos; // 选择图片的最小数,默认是9张图片最大也是9张 pickerVc.maxCount = 9; self.presentVC(pickerVc); // 用block来回调 __weak typeof(self) weakSelf = self; pickerVc.callBack = ^(NSArray *assets){ //遍历获取每一张图片 并转成二进制 for (ZLPhotoAssets *asset in assets) { NSData *imageData = UIImagePNGRepresentation(asset.originImage); //给图片起随机名字 NSString *filename = [NSString stringWithFormat:@"%d.png",arc4random_uniform(100)]; //保存到fileDict中 [weakSelf.fileDict setObject:imageData forKey:filename]; } }; } - (IBAction)oploadPicture:(id)sender { [self original]; } - (void)original { //创建管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *url = @"http://www.baidu.cn/index.php/Home/Index/ugc_tipic"; [manager.requestSerializer setValue:@"application/json, image/png" forHTTPHeaderField:@"Accept"]; // [manager.requestSerializer setValue:url.absoluteString forHTTPHeaderField:@"Referer"]; // 加密 NSString *mdSecret = [DGSecret md5:[DGGlobel getInstance].secret]; NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [dic setValue:[DGGlobel getInstance].user_id forKey:@"user_id"]; [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [self.fileDict enumerateKeysAndObjectsUsingBlock:^(NSString *saveFliename, NSData *fileData, BOOL * _Nonnull stop) { //获取到每个文件的二进制数据 拼接文本参数 [formData appendPartWithFileData:fileData name:@"file" fileName:saveFliename mimeType:@"image/jpg"]; }]; } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSDictionary *content = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"上传成功content = %@",content); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"上传失败%@",[error localizedDescription]); }]; } @end </code>
Thinkphp處理文件:
<code>$ugc_topic = M('ugc_topic'); $ugc_image_type = M('ugc_image_type'); $tmp_str = ''; $upload = $_POST; foreach($upload as $value => $key) { $tmp_str.= '-----'.$key.'=>'.$value."\n\r"; } // ----------------调试程序---------------------- $filename = dirname(__FILE__).'/file.txt'; $now_time = date('Y-m-d H:i:s' , time()); $word2 = "{$now_time}\n\r{$tmp_str}\n\r\n\r"; $fh = fopen($filename, "a+"); echo fwrite($fh, $word2); fclose($fh); $user_id = I('post.user_id','','htmlspecialchars'); // 当前登陆成功的用户id $title = I('post.title','','htmlspecialchars'); // 当前发布话题的标题 $content = I('post.content','','htmlspecialchars'); // 当前发布话题的内容 $remind_who = I('post.remind_who','','htmlspecialchars'); // 提醒谁看的用户id $image_name = I('post.image_name','','htmlspecialchars'); // 当前发布话题的图片 header("Content-Type: application/octet-stream"); $byte = $_POST['image_name']; $byte = str_replace(' ','',$byte); //处理数据 $byte = str_ireplace("<",'',$byte); $byte = str_ireplace(">",'',$byte); $byte = pack("H*",$byte); //16进制转换成二进制 $filename2 = dirname(__FILE__).'/file.txt'; $word22 = "\n\r\n\r{$byte}\n\r\n\r"; $fhf = fopen($filename2, "a+"); echo fwrite($fhf, $word22); fclose($fhf); header('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); // 将图片保存到相应位置 header('Content-type: text/json; charset=UTF-8' );</code>
請賜教~多謝!
回覆內容:
剛開始接觸APP端程序處理。
現在問題就卡在TP端接收IOS傳過來的圖片,請問TP端處理上傳的圖片資料該是如何流程?要注意些什麼問題,例如資料格式應該是什麼?
請問下面的處理方式正確嗎?
ios檔案如下:
XLSelectView.h檔案:
<code>// XLSelectView.h // XLUploadImages // Created by 薛林 on 16/6/18. // Copyright © 2016年 xuelin. All rights reserved. #import <UIKit/UIKit.h> @class ZLPhotoPickerViewController; @interface XLSelectView : UIView //跳转界面的block @property (nonatomic, copy) void(^presentVC)(ZLPhotoPickerViewController *pickerVC); //网络需要传入的参数 @property (nonatomic, copy) NSString *postUrlString; //parameters @property (nonatomic, strong) NSDictionary *parameters; //后台接收图片的字段 @property (nonatomic, copy) NSString *userfile; //加载xib + (instancetype)loadnib; @end </code>
XLSelectView.m檔:
<code>// XLSelectView.m // XLUploadImages // // Created by 薛林 on 16/6/18. // Copyright © 2016年 xuelin. All rights reserved. // #import "XLSelectView.h" #import "ZLPhoto.h" #import "AFNetworking.h" #import "DGGlobel.h" #import "DGSecret.h" @interface XLSelectView () //保存图片二进制数据 @property (nonatomic, strong) NSMutableDictionary *fileDict; @end @implementation XLSelectView #pragma mark - 懒加载字典 - (NSMutableDictionary *)fileDict { if (_fileDict == nil) { _fileDict = [NSMutableDictionary dictionary]; } return _fileDict; } #pragma mark - 加载xib + (instancetype)loadnib { return [[[NSBundle mainBundle]loadNibNamed:@"XLSelectView" owner:nil options:nil]lastObject]; } - (IBAction)selectMorePic:(id)sender { // 创建图片多选控制器 ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init]; // 默认显示相册里面的内容SavePhotos pickerVc.status = PickerViewShowStatusSavePhotos; // 选择图片的最小数,默认是9张图片最大也是9张 pickerVc.maxCount = 9; self.presentVC(pickerVc); // 用block来回调 __weak typeof(self) weakSelf = self; pickerVc.callBack = ^(NSArray *assets){ //遍历获取每一张图片 并转成二进制 for (ZLPhotoAssets *asset in assets) { NSData *imageData = UIImagePNGRepresentation(asset.originImage); //给图片起随机名字 NSString *filename = [NSString stringWithFormat:@"%d.png",arc4random_uniform(100)]; //保存到fileDict中 [weakSelf.fileDict setObject:imageData forKey:filename]; } }; } - (IBAction)oploadPicture:(id)sender { [self original]; } - (void)original { //创建管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; NSString *url = @"http://www.baidu.cn/index.php/Home/Index/ugc_tipic"; [manager.requestSerializer setValue:@"application/json, image/png" forHTTPHeaderField:@"Accept"]; // [manager.requestSerializer setValue:url.absoluteString forHTTPHeaderField:@"Referer"]; // 加密 NSString *mdSecret = [DGSecret md5:[DGGlobel getInstance].secret]; NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [dic setValue:[DGGlobel getInstance].user_id forKey:@"user_id"]; [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { [self.fileDict enumerateKeysAndObjectsUsingBlock:^(NSString *saveFliename, NSData *fileData, BOOL * _Nonnull stop) { //获取到每个文件的二进制数据 拼接文本参数 [formData appendPartWithFileData:fileData name:@"file" fileName:saveFliename mimeType:@"image/jpg"]; }]; } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSDictionary *content = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"上传成功content = %@",content); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"上传失败%@",[error localizedDescription]); }]; } @end </code>
Thinkphp處理文件:
<code>$ugc_topic = M('ugc_topic'); $ugc_image_type = M('ugc_image_type'); $tmp_str = ''; $upload = $_POST; foreach($upload as $value => $key) { $tmp_str.= '-----'.$key.'=>'.$value."\n\r"; } // ----------------调试程序---------------------- $filename = dirname(__FILE__).'/file.txt'; $now_time = date('Y-m-d H:i:s' , time()); $word2 = "{$now_time}\n\r{$tmp_str}\n\r\n\r"; $fh = fopen($filename, "a+"); echo fwrite($fh, $word2); fclose($fh); $user_id = I('post.user_id','','htmlspecialchars'); // 当前登陆成功的用户id $title = I('post.title','','htmlspecialchars'); // 当前发布话题的标题 $content = I('post.content','','htmlspecialchars'); // 当前发布话题的内容 $remind_who = I('post.remind_who','','htmlspecialchars'); // 提醒谁看的用户id $image_name = I('post.image_name','','htmlspecialchars'); // 当前发布话题的图片 header("Content-Type: application/octet-stream"); $byte = $_POST['image_name']; $byte = str_replace(' ','',$byte); //处理数据 $byte = str_ireplace("<",'',$byte); $byte = str_ireplace(">",'',$byte); $byte = pack("H*",$byte); //16进制转换成二进制 $filename2 = dirname(__FILE__).'/file.txt'; $word22 = "\n\r\n\r{$byte}\n\r\n\r"; $fhf = fopen($filename2, "a+"); echo fwrite($fhf, $word22); fclose($fhf); header('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); // 将图片保存到相应位置 header('Content-type: text/json; charset=UTF-8' );</code>
請賜教~多謝!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP在數據庫操作和服務器端邏輯處理中使用MySQLi和PDO擴展進行數據庫交互,並通過會話管理等功能處理服務器端邏輯。 1)使用MySQLi或PDO連接數據庫,執行SQL查詢。 2)通過會話管理等功能處理HTTP請求和用戶狀態。 3)使用事務確保數據庫操作的原子性。 4)防止SQL注入,使用異常處理和關閉連接來調試。 5)通過索引和緩存優化性能,編寫可讀性高的代碼並進行錯誤處理。
