我整个上午都在寻找一个清晰的例子,说明如何将用 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)
我的问题是:
- 我仍然可以使用我的 Objective-C JSON 调用将图片上传到服务器还是必须完全改变上传图片的方式?
- 如果可能的话,如何更改 Python 服务器代码以从 JSON 中获取图片?