[英]HTTPPost multipart (upload file) from Java to Python webapp2
我正在嘗試將文件上傳到GAE-服務器端代碼:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0] # When using flask, request.files[0] gives correct output.
self.response.out.write('/serve/%s' % blob_info.key())
使用HTML,我可以使其正常工作:
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit"
name="submit" value="Submit"> </form></body></html>""")
但是我必須能夠從Java發出多部分的發布請求。 我在openshift上托管了一個flask項目(燒瓶, request.files[0]
代替) ,其中Java代碼似乎可以正常工作:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
DefaultHttpClient mHttpClient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(getString(R.string.url_webservice) + "/upload");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("file", new FileBody(new File(path)));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new MyUploadResponseHandler(path));
但是當我在GAE上運行它時,我在上傳時無法在上載文件upload_files[0]
上獲得索引-錯誤在哪里? 我似乎找不到它,代碼與我確認可以工作的以下代碼非常相似(燒瓶,openshift) :
def upload_file():
if request.method == 'POST':
file = request.files['file']
...
更新:完整的錯誤日志:
list index out of range
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "myapp.py", line 22, in post
blob_info = upload_files[0]
IndexError: list index out of range
blobstore.create_upload_url('/upload')
尚未在Java中生成url /upload
,/ upload是您嘗試發布以查看該處理程序生成的html的位置,您將看到表單的操作url為不同。
您可以讓處理程序以您的Java代碼獲取然后用於發布的上傳網址作為響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.