在 captionmash.com 上工作时,我不得不解决类似的问题(将单张照片从 Flex 上传到 Django),也许它可以帮助你。我使用 PyAMF 进行普通消息传递,但 FileReference 类有一个内置的上传方法,所以我选择了简单的方法。
基本上系统允许您将单个文件从 Flex 上传到 Google App Engine,然后它使用 App Engine 的 Image API 创建缩略图并将图像转换为 JPEG,然后将其上传到 S3 存储桶。boto库用于 Amazon S3 连接,您可以在 github 上查看项目的整个代码。
此代码仅用于单个文件上传,但您应该能够通过创建一个 FileReference 对象数组并在所有这些对象上调用 upload 方法来进行多文件上传。
我在这里发布的代码有点清理,如果你仍然有问题,你应该检查 repo。
客户端(弹性):
private function upload(fileReference:FileReference,
album_id:int,
user_id:int):void{
try {
//500 kb image size
if(fileReference.size > ApplicationConstants.IMAGE_SIZE_LIMIT){
trace("File too big"+fileReference.size);
return;
}
fileReference.addEventListener(Event.COMPLETE,onComplete);
var data:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest(ApplicationConstants.DJANGO_UPLOAD_URL);
request.method = URLRequestMethod.POST;
request.data = data;
fileReference.upload(request,"file");
//Popup indefinite progress bar
} catch (err:Error) {
trace("ERROR: zero-byte file");
}
}
//When upload complete
private function onComplete(evt:Event):void{
fileReference.removeEventListener(Event.COMPLETE,onComplete);
//Do other stuff (remove progress bar etc)
}
服务器端(App Engine 上的 Django):
网址:
urlpatterns = patterns('',
...
(r'^upload/$', receive_file),
...
意见:
def receive_file(request):
uploadService = UploadService()
file = request.FILES['file']
uploadService.receive_single_file(file)
return HttpResponse()
上传服务类
import uuid
from google.appengine.api import images
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import mimetypes
import settings
def receive_single_file(self,file):
uuid_name = str(uuid.uuid4())
content = file.read()
image_jpeg = self.create_jpeg(content)
self.store_in_s3(uuid_name, image_jpeg)
thumbnail = self.create_thumbnail(content)
self.store_in_s3('tn_'+uuid_name, thumbnail)
#Convert image to JPEG (also reduce size)
def create_jpeg(self,content):
img = images.Image(content)
img_jpeg = images.resize(content,img.width,img.height,images.JPEG)
return img_jpeg
#Create thumbnail image using file
def create_thumbnail(self,content):
image = images.resize(content,THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,images.JPEG)
return image
def store_in_s3(self,filename,content):
conn = S3Connection(settings.ACCESS_KEY, settings.PASS_KEY)
b = conn.get_bucket(BUCKET_NAME)
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = filename
k.set_metadata("Content-Type", mime)
k.set_contents_from_string(content)
k.set_acl("public-read")