2016-08-24 41 views
8

當設置的燒瓶中的服務器,我們可以嘗試通過如何接收上傳的文件與克萊因瓶一樣在Python

imagefile = flask.request.files['imagefile'] 
filename_ = str(datetime.datetime.now()).replace(' ', '_') + \ 
    werkzeug.secure_filename(imagefile.filename) 
filename = os.path.join(UPLOAD_FOLDER, filename_) 
imagefile.save(filename) 
logging.info('Saving to %s.', filename) 
image = exifutil.open_oriented_im(filename) 

接收上傳的文件,用戶當我在看Klein文件,我已經看到http://klein.readthedocs.io/en/latest/examples/staticfiles.html,但是這似乎是從web服務提供文件,而不是接收已上傳到Web服務的文件。如果我想讓我的Klein服務器能夠收到abc.jpg並將其保存在文件系統中,是否有任何文檔可以指導我實現該目標?

+1

您應該能夠以提取文件中的一個HTTP請求(通常爲POST),就像任何其他變量。看起來克萊因基於扭曲,所以也許[這個人的解決方案](http://www.cristinagreen.com/uploading-files-using-twisted-web.html)將爲你工作。 –

+0

謝謝,我會看看。 – JLTChiu

回答

2

由於Liam Kelly評論說,從this post的片段應該工作。使用cgi.FieldStorage可以在不明確發送文件元數據的情況下輕鬆發送文件元數據。克萊因/扭曲的做法將是這個樣子:

from cgi import FieldStorage 
from klein import Klein 
from werkzeug import secure_filename 

app = Klein() 

@app.route('/') 
def formpage(request): 
    return ''' 
    <form action="/images" enctype="multipart/form-data" method="post"> 
    <p> 
     Please specify a file, or a set of files:<br> 
     <input type="file" name="datafile" size="40"> 
    </p> 
    <div> 
     <input type="submit" value="Send"> 
    </div> 
    </form> 
    ''' 

@app.route('/images', methods=['POST']) 
def processImages(request): 
    method = request.method.decode('utf-8').upper() 
    content_type = request.getHeader('content-type') 

    img = FieldStorage(
     fp = request.content, 
     headers = request.getAllHeaders(), 
     environ = {'REQUEST_METHOD': method, 'CONTENT_TYPE': content_type}) 
    name = secure_filename(img[b'datafile'].filename) 

    with open(name, 'wb') as fileOutput: 
     # fileOutput.write(img['datafile'].value) 
     fileOutput.write(request.args[b'datafile'][0]) 

app.run('localhost', 8000) 

不管出於什麼原因,我的Python 3.4(Ubuntu的14.04)的cgi.FieldStorage版本不返回正確的結果。我在Python 2.7.11上測試了它,它工作正常。據說,你也可以在前端收集文件名和其他元數據,並通過ajax調用發送給klein。這樣你就不必在後端做太多的處理(這通常是件好事)。或者,您可以瞭解如何使用werkzeug提供的實用程序。功能werkzeug.secure_filenamerequest.files(即FileStorage)並不特別難於實現或重新創建。

相關問題