1. 程式人生 > >圖片上傳至資料庫(新浪雲)的方法

圖片上傳至資料庫(新浪雲)的方法

        在程式開發中,經常會遇到上傳圖片的問題,那麼,下面的一段程式碼可以幫助你將圖片上傳至伺服器(本篇程式碼用的伺服器是新浪雲的SAE,伺服器端的程式碼是用thinkPHP編寫,會在後面貼出)。

        直接上程式碼:

先匯入AFN的庫和標頭檔案

-(void)savepicture
{
   NSString *url = imageUrl;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        UIImage *image = [UIImage imageNamed:@"head6.png"];
        NSData *imageData = UIImageJPEGRepresentation(image,0.1);//壓縮圖片 壓縮至十分之一
        [formData appendPartWithFileData:imageData name:@"user_header_image" fileName:@"image.png" mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);

    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        
    }];

}

thinkPHP寫儲存圖片的程式碼有幾種,下面就介紹一種簡單常用的:
    // 這個系統自帶 框架帶的
    public function upload() {
        // 注意此方法本身就支援多張圖片的上傳
        $upload = new \Think\Upload();
        $upload ->maxSize = 0; // 不限制圖片的大小
        // 錯誤的原因是沒有將附加的格式寫入,新增png到陣列中即可,讓伺服器支援
        $upload ->exts = array('jpg','gif','jpeg','png', 'zip');
        $upload ->rootPath = '.ciellstorage/img/';
        $upload ->savePath = 'header/'; //儲存在“header”目錄下,header目錄是已經存在的
        $upload->saveName = array('uniqid',''); // 伺服器自動生成一個唯一的檔名 演算法 SHA-1類似演算法唯一檔名
        // 取消自動使用子目錄儲存上傳檔案
        $upload ->autoSub = false;
        //$upload->subName = array('date','Ymd');
        $info = $upload -> upload();
        if(!$info){
            $reutnResult['code']= '0';
            $reutnResult['message'] =$upload->getError();
        }else {
            $reutnResult['code']= '1';
            $reutnResult['message'] = $info['user_header_image']['url'];
            // 取出info裡面的儲存的圖片名稱進行進一步操作
            // 儲存檔名稱到資料庫中
        }
        $this ->ajaxReturn($reutnResult);
    }

如果有想知道新浪雲的使用可以留言。