使用Python和Alfresco API上传文件

时间:2015-05-21 09:31:41

标签: python curl upload alfresco

我遇到了Alfresco和Python的问题:我想直接用Python上传一个新文件。每次我尝试都会收到HTTP 500错误但没有详细信息...

我首先尝试使用CURL以确保它正常工作并且文件上传没有问题。

我使用了以下curl命令行:

url -X POST -uadmin:admin "http://localhost:8080/alfresco/service/api/upload" -F filedata=@/tmp/eeeeee.pdf -F siteid=test -F containerid=documentLibrary

在我的Python脚本中,我尝试了PyCurl,现在是简单的urllib。我认为问题来自文件作为参数给出的方式。

使用PyCurl的Python代码:

c = pycurl.Curl()
params = {'containerid': 'documentLibrary', 'siteid': 'test', 'filedata': open('/tmp/eeeeee.pdf', 'rb')}
c.setopt(c.URL, 'http://localhost:8080/alfresco/service/api/upload')
c.setopt(c.POST, 1)
c.setopt(c.POSTFIELDS, urllib.urlencode(params))
c.setopt(c.USERPWD, 'admin:admin')
c.perform()

此代码示例导致:

 {
    "code" : 500,
    "name" : "Internal Error",
    "description" : "An error inside the HTTP server which prevented it from fulfilling the request."
  },  

  "message" : "04200017 Unexpected error occurred during upload of new content."

有人知道如何实现这一目标吗?

1 个答案:

答案 0 :(得分:7)

您可以使用非常简单的库Requests

import json
import requests

url = "http://localhost:8080/alfresco/service/api/upload"
auth = ("admin", "admin")
files = {"filedata": open("/tmp/foo.txt", "rb")}
data = {"siteid": "test", "containerid": "documentLibrary"}
r = requests.post(url, files=files, data=data, auth=auth)
print(r.status_code)
print(json.loads(r.text))

输出:

200
{'fileName': 'foo.txt',
 'nodeRef': 'workspace://SpacesStore/37a96447-44b0-4aaa-b6ff-98dae1f12a73',
 'status': {'code': 200,
  'description': 'File uploaded successfully',
  'name': 'OK'}}