从命令行Java应用程序向Google App Engine的BlobStore上传
这是我用来上传文件到Blobstore的服务器端代码,适用于命令行应用:
public class UploadServlet extends HttpServlet
{
private static final Logger log = Logger.getLogger(UploadServlet.class.getName());
private final BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
final Map<String, BlobKey> blobs = bs.getUploadedBlobs(request);
final BlobKey blobKey = blobs.get("blob");
if (blobKey == null)
{
log.severe("BlobKey was null!");
response.sendRedirect("/error.html");
}
else
{
response.sendRedirect("/image?blob-key=" + blobKey.getKeyString());
}
}
/**
* Generates the custom single use blobstore URL's that are needed to upload to the blobstore programmatically. */
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
final String uploadURL = bs.createUploadUrl("/upload");
final PrintWriter pw = response.getWriter();
response.setContentType("text/plain");
pw.write(uploadURL);
}
}
我已经在本地开发模式的服务器上让以下代码正常工作了,没有使用身份验证的代码,所以我知道这个multipart/form
的代码是没问题的。但是加上身份验证代码后,就出现了以下错误:
r = opener.open(request)
File "C:\Python26\lib\urllib2.py", line 397, in open
response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 435, in error
return self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 369, in _call_chain
result = func(*args)
File "C:\Python26\lib\urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 302: Found
我把命令行客户端的代码从Java换成了Python:
f = urllib2.urlopen('http://myapp.appspot.com/upload')
bloburl = f.read(1024)
print bloburl
print
image = file('120.jpg', 'r')
form = MultiPartForm()
form.add_file('blob', 'blob', image, 'image/jpeg')
request = urllib2.Request(bloburl)
body = str(form)
request.add_header('Content-type', form.get_content_type())
request.add_header('Content-length', len(body))
request.add_data(body)
opener = auth.get_auth_opener('myapp', 'username', 'password')
r = opener.open(request)
data = r.read()
print data
我只想要一个简单的命令行工具,可以接收一个文件并把它上传到BlobStore。我在网上找不到一个完整的例子。虽然有很多例子是在GAE上完成所有工作的,但没有一个是从独立客户端进行POST
请求的命令行客户端。