2017-05-12 98 views
0

我正在訪問一個網站,我想上傳一個文件。python請求上傳文件

我寫在Python代碼:

import requests 

url = 'http://example.com' 
files = {'file': open('1.jpg', 'rb')} 
r = requests.post(url, files=files) 
print(r.content) 

但似乎沒有文件已被上傳,頁面是一樣的最初一個。

我想知道如何上傳文件。

該頁面的源代碼:

<html><head><meta charset="utf-8" /></head> 

<body> 
<br><br> 
Upload<br><br> 
<form action="upload.php" method="post" 
enctype="multipart/form-data"> 
<label for="file">Filename:</label> 
<input type="hidden" name="dir" value="/uploads/" /> 
<input type="file" name="file" id="file" /> 
<br /> 
<input type="submit" name="submit" value="Submit" /> 
</form> 

</body> 
</html> 
+0

順便說一句,你沒有發送'dir'。 'r = requests.post(url,files = files,data = {「dir」:「/ uploads /」})' – ozgur

+0

@OzgurVatansever我已經添加了數據。但仍然沒有文件上傳。 –

回答

1

的幾點:

  • 確保您的請求提交到正確的URL(形式爲「行動」)
  • 使用data參數提交其他表單字段(「目錄」,「提交')
  • 包括在files的文件的名稱(這是可選的)

代碼:

import requests 

url = 'http://example.com' + '/upload.php' 
data = {'dir':'/uploads/', 'submit':'Submit'} 
files = {'file':('1.jpg', open('1.jpg', 'rb'))} 
r = requests.post(url, data=data, files=files) 

print(r.content) 
+0

謝謝。它現在有效。似乎我有錯誤的網址來上傳文件。 –

0

首先,定義上載目錄類似的路徑,

app.config['UPLOAD_FOLDER'] = 'uploads/' 

然後定義這使得像上傳文件的擴展名,

app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 

現在假設你調用函數來處理上傳文件,那麼你必須編寫類似於代碼的代碼s,

# Route that will process the file upload 
@app.route('/upload', methods=['POST']) 
def upload(): 
    # Get the name of the uploaded file 
    file = request.files['file'] 

    # Check if the file is one of the allowed types/extensions 
    if file and allowed_file(file.filename): 
     # Make the filename safe, remove unsupported chars 
     filename = secure_filename(file.filename) 

     # Move the file form the temporal folder to 
     # the upload folder we setup 
     file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 

     # Redirect the user to the uploaded_file route, which 
     # will basicaly show on the browser the uploaded file 
     return redirect(url_for('YOUR REDIRECT FUNCTION NAME',filename=filename)) 

這樣您就可以上傳文件並將其存儲在您所在的文件夾中。

我希望這會幫助你。

謝謝。

+0

感謝您的回覆。其實,我只是訪問他人擁有的網站。我可以通過瀏覽器上傳文件,但我需要找到一種通過python上傳的方法。 –