2013-02-24 66 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' 

मैं इस कोड करने के लिए कोशिश कर रहा हूँ लेकिन यह काम नहीं कर रहा है। मैं क्या गलत कर रहा हूँ? से बोतल-0,12FileUpload वर्ग

+4

'get_save_path_for_category' बोतल दस्तावेज़ में उपयोग किया गया एक उदाहरण है और बोतल एपीआई का हिस्सा नहीं है। 'Save_path' को'/tmp' या कुछ सेट करने का प्रयास करें। अगर इससे मदद नहीं मिलती है: त्रुटियों को पोस्ट करें ... – robertklep

+2

और: upload.save() विधि बोतल-0.12dev का हिस्सा है जो अभी तक जारी नहीं है। यदि आप बोतल 0.11 (नवीनतम स्थिर रिलीज) का उपयोग करते हैं तो स्थिर दस्तावेज़ देखें। – defnull

+0

आपको यह त्रुटि मिलती है "AttributeError बढ़ाएं, नाम विशेषताएँ त्रुटि: सहेजें"? .. – Hamoudaq

उत्तर

23

शुरू इसकी 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') के साथ open_file' के रूप में, अन्यथा आपको 'TypeError: str होना चाहिए, बाइट्स नहीं होना चाहिए' त्रुटि –