我今天早上花了一整天的時間尋找一個清晰的例子,說明如何將使用iPhone拍攝的照片上傳到blobstore,但沒有成功。將圖片從iPhone上傳到GAE 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的部分這個作品是(I」中號使用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];
}
}];
這工作正常並且圖像被保存在服務器上。但是我想要對無法保存文件的數據存儲進行同樣的處理。所以我建立了一個網頁來練習保存圖像,並且我可以從標準的網頁表單上在沒有任何問題的情況下上傳圖像。這是我使用它保存在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)
我的問題是:
- 我還可以用我的Objective-C JSON調用將圖片上傳到服務器,或者我必須徹底改變上傳圖片的方式嗎?
- 如果可能,我如何更改Python服務器代碼以從JSON獲取圖片?
沒有想法?任何人都可以幫忙需要更多細節? – Eagle