Django上传图片 - 从表单到Rackspace/S3,无需处理
我想通过一个表单上传一张图片(JPG格式),然后把这张图片发送到Rackspace的“云文件”或者亚马逊的“S3”。
- 不需要对文件进行任何处理。
- 不需要保存到硬盘上,所有操作都在内存中进行(我是在云服务器上托管的)。
- 图片大小不会超过75KB。
更新(两个注意事项):
- 第一:它还需要在手机应用发送数据时也能正常工作。
- 第二:需要同时发送到Rackspace的云文件和S3(先从云文件开始)。
下面的代码可以工作,但实在是太复杂了。
import cloudfiles as cf
def uploadImage(request, id):
cf_con = cf.get_connection(username='YYY', api_key='XXX', serviceNet=True)
container = cf_con.get_container('container_name')
file = request.FILES["item_photo"]
f = StringIO(file.read())
f = Image.open(f)
### Only works if I resize for some reason, otherwise uploads a broken file
image = f.resize((600,600), Image.ANTIALIAS)
o = StringIO()
image.save(o, "JPEG", quality=80)
image = o.getvalue()
file_name = "%s/%s" % (id, '600x600.jpeg')
### This simply uploads to Rackspace Cloud files.
put_file(container, file_name, image)
非常感谢,
希望一切都好……
d.
2 个回答
2
搞定了。找到了一种更简单、更优雅的方法,感觉自己之前没想到真是太傻了。
file = request.FILES["item_photo"]
file_name = "%s/%s" % (id, '600.jpeg')
put_file(container, file_name, file.read())
3
那我们干脆不使用Python,直接上传到S3怎么样?
你可以设置你的S3存储桶,不允许上传超过$X字节的文件。
下面是一个简单的例子,来说明如何直接上传到S3(不考虑你的图片宽度/高度条件)。
http://sente.cc/upload_to_s3.html
代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h3>refresh the page after you've submitted to see your new image</h3>
<div style="width:300px">
<form action="http://s3.amazonaws.com/dev.sente" method="post" enctype="multipart/form-data">
<fieldset>
<input type="hidden" name="acl" value="public-read" /> <br />
<i>name of key:</i><input type="text" name="key" readonly="true" value="image.jpg" /> <br />
<input name="file" type="file" /> <br />
<input name="submit" value="Upload" type="submit" />
</fieldset>
</form>
</div>
<br>
<a href="http://s3.amazonaws.com/dev.sente/image.jpg">http://s3.amazonaws.com/dev.sente/image.jpg</a>
<br>
<a href="http://s3.amazonaws.com/dev.sente/image.jpg"><img src="http://s3.amazonaws.com/dev.sente/image.jpg"></a>
</a>
</body>
</html>