将图像从iphone上传到GAE blobstore

时间:2013-07-08 10:04:03

标签: python iphone image google-app-engine blobstore

今天早上我花了很多时间寻找一个关于如何将用iPhone拍摄的照片上传到blobstore的明确示例,但没有成功。

目前我开发了我的iPhone应用程序,可以使用PHP中的代码将服务器中的图片发送到服务器:

// Function to upload a photo in a file and save data in the DB
function upload($photoData, $descr, $phone) {
    // Folder to upload data
    $path = $_SERVER['DOCUMENT_ROOT']."/program/data/";

    // Check if there was no error during the file upload
    if ($photoData['error'] == 0) {
        $result = query("INSERT INTO pics(descr, phone) VALUES('%s','%s')", $descr, $phone);
        if (!$result['error']) {
            // Inserted in the database, go on with file storage
            // Obtain database link (in lib.php)
            global $link;

            // Get the last automatically generated ID
            $idPhoto = mysqli_insert_id($link);

            // Move the temporarily stored file to a convenient location
            if (move_uploaded_file($photoData['tmp_name'], $path.$idPhoto.".jpg")) {
                // File moved, all good, generate thumbnail
                thumb($path.$idPhoto.".jpg", 180);
                print json_encode(array('successful' => 1));
            } else {
                errorJson('Upload on server problem');
            }
        } else {
            errorJson('Save database problem: '.$result['error']);
        }
    } else {
        errorJson('Upload malfunction.');
    }
}

Objective-C中使其工作的部分是(我正在使用AFNetworking,而对象API sharedInstance是一个AFJSONRequestOperation类):

// Upload the image and the description to the web service
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                             @"upload", @"command",
                                             UIImageJPEGRepresentation(originalPhoto, 70), @"file",
                                             description, @"descr",
                                             phoneNumber, @"phone",
                                             nil]
                               onCompletion:^(NSDictionary *json) {
                                   // Finished and response from server
                                   if (![json objectForKey:@"error"]) {
                                       // Success
                                       [[[UIAlertView alloc]initWithTitle:@"Info"
                                                                  message:@"Thanks"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"Dismiss"
                                                        otherButtonTitles: nil] show];

                                       // Send a notification so the main view can reload the data
                                       [[NSNotificationCenter defaultCenter] postNotificationName:@"updateStream" object:nil];
                                   } else {
                                       // Error
                                       NSString* errorMsg = [json objectForKey:@"error"];
                                       [UIAlertView error:errorMsg];
                                   }
                               }];

此工作正常,图像保存在服务器上。但是我想对数据存储区做同样的事情,你无法保存文件。所以我创建了一个网页来练习保存图像,我可以从标准网页表单上下载blobstore中没有任何问题的图像。这是我用来将它保存在GAE中的代码(忘记我自己的帮助器类或函数,如PicturePageHandler或render_page):

# Get and post for the create page
class Create(PicturePageHandler, blobstore_handlers.BlobstoreUploadHandler):
    def get(self):
        if self.user_logged_in():
            # The session for upload a file must be new every reload page
            uploadUrl = blobstore.create_upload_url('/addPic')
            self.render_page("addPicture.htm", form_action=uploadUrl)

    def post(self):
        if self.user_logged_in():
            # Create a dictionary with the values, we will need in case of error
            templateValues = self.template_from_request()
            # Test if all data form is valid
            testErrors = check_fields(self)

            if testErrors[0]:
                # No errors, save the object
                try:
                    # Get the file and upload it
                    uploadFiles = self.get_uploads('picture')
                    # Get the key returned from blobstore, for the first element
                    blobInfo = uploadFiles[0]
                    # Add the key and the permanent url to the template
                    templateValues['blobKey'] = blobInfo.key()
                    templateValues['servingUrl'] = images.get_serving_url(blobInfo.key(), size=None)

                    # Save all
                    pic = Picture.save(self.user.key, **templateValues)
                    if pic is None:
                        logging.error('Picture save error.')

                    self.redirect("/myPics")

                except:
                    self.render_page("customMessage.htm", custom_msg=_("Problems while uploading the picture."))
            else:
                # Errors, render the page again, with the values, and showing the errors
                templateValues = custom.prepare_errors(templateValues, testErrors[1])
                # The session for upload a file must be new every reload page
                templateValues['form_action'] = blobstore.create_upload_url('/addPic')

                self.render_page("addPicture.htm", **templateValues)

我的问题是:

  1. 我是否仍然可以使用Objective-C JSON调用将图片上传到服务器,还是必须完全更改上传图片的方式?
  2. 如果可能,我如何更改Python服务器代码以从JSON获取图片?

1 个答案:

答案 0 :(得分:0)