2017-05-12 4 views
0

웹 사이트를 방문하고 있는데 파일을 업로드하고 싶습니다. 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

Btw, 당신은'dir'을 보내지 않았습니다. 'r = requests.post (url, files = files, data = { "dir": "/ uploads /"})' – ozgur

+0

@OzgurVatansever 데이터를 추가했습니다. 그러나 여전히 파일은 업로드되지 않습니다. –

답변

1

몇 가지 포인트 :

  • 올바른 URL (양식 '행동')
  • 가 다른 양식 필드 ('디렉토리'를 제출 data 매개 변수를 사용하여 요청을 제출해야합니다 '제출

    012 ')
  • (이것은 선택 사항입니다)

코드 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

감사합니다. 이제 작동합니다. 파일 업로드에 잘못된 URL이있는 것으로 보입니다. –

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

답장을 보내 주셔서 감사합니다. 사실, 나는 다른 사람들이 소유 한 웹 사이트를 방금 방문하고 있습니다. 내 브라우저를 통해 파일을 업로드 할 수 있지만 파이썬을 통해 업로드 할 수있는 방법을 찾아야합니다. –