2013-02-24 3 views
11

HTML 사용하여 파일을 저장하는 방법 :업로드하고 병 프레임 워크를

<form action="/upload" method="post" enctype="multipart/form-data"> 
    Category:  <input type="text" name="category" /> 
    Select a file: <input type="file" name="upload" /> 
    <input type="submit" value="Start upload" /> 
</form> 

보기 :이 코드를 할 노력하고있어

@route('/upload', method='POST') 
def do_login(): 
    category = request.forms.get('category') 
    upload  = request.files.get('upload') 
    name, ext = os.path.splitext(upload.filename) 
    if ext not in ('png','jpg','jpeg'): 
     return 'File extension not allowed.' 

    save_path = get_save_path_for_category(category) 
    upload.save(save_path) # appends upload.filename automatically 
    return 'OK' 

하지만이 작동하지 않습니다. 내가 뭘 잘못하고있어?

+4

'get_save_path_for_category'는 Bottle 문서에서 사용되고 Bottle API의 일부가 아닌 예입니다. 'save_path'를'/ tmp' 또는 무엇인가로 설정하십시오. 그게 도움이되지 않는 경우 : 게시 오류 ... – robertklep

+2

그리고 : upload.save() 메소드는 아직 풀리지 않은 bottle-0.12dev의 일부입니다. 병 0.11 (최신 안정 릴리스)을 사용하는 경우 안정적인 문서를 참조하십시오. – defnull

+0

이 오류가 발생합니다. "raise AttributeError, name AttributeError : save"? .. – Hamoudaq

답변

23

병 0.12FileUpload 클래스에서 시작은 그 upload.save() 기능을 구현했다. 여기

은 예를 들어 인 병 - 0.12 :

import os 
from bottle import route, request, static_file, run 

@route('/') 
def root(): 
    return static_file('test.html', root='.') 

@route('/upload', method='POST') 
def do_upload(): 
    category = request.forms.get('category') 
    upload = request.files.get('upload') 
    name, ext = os.path.splitext(upload.filename) 
    if ext not in ('.png', '.jpg', '.jpeg'): 
     return "File extension not allowed." 

    save_path = "/tmp/{category}".format(category=category) 
    if not os.path.exists(save_path): 
     os.makedirs(save_path) 

    file_path = "{path}/{file}".format(path=save_path, file=upload.filename) 
    upload.save(file_path) 
    return "File successfully saved to '{0}'.".format(save_path) 

if __name__ == '__main__': 
    run(host='localhost', port=8080) 

참고 os.path.splitext() 함수에 확장을 제공 "<EXT>."형식이 아니라 "<EXT> ".

  • 당신이 병 - 0.12, 변화에 이전 버전을 사용하는 경우 :

    ... 
    upload.save(file_path) 
    ... 
    

에 :

... 
    with open(file_path, 'w') as open_file: 
     open_file.write(upload.file.read()) 
    ... 
  • 실행 서버;
  • 브라우저에 "localhost : 8080"을 입력하십시오.
+0

'open (file_path, 'wb') with open_file' 그렇지 않으면'TypeError : 바이트가 아니라 str이어야합니다 .' 오류 –

관련 문제