[英]Upload files with FileDrop.js on a Python Flask server
我運行一個Python Flask應用程序,並希望實現將文件上傳到服務器的可能性。 FileDrop.js看起來很有前途,但是,我不認為它可以與Flask一起使用。
造成這種情況的原因似乎是Flask希望通過POST將文件與用於從應用程序中識別文件的附加參數一起發送到服務器。 我使用另一個文件上傳框架jQuery filedrop進行了此工作:
<html>
<head>
<script type="text/javascript" src="https://github.com/weixiyen/jquery-filedrop/blob/master/jquery.filedrop.js"></script>
</head>
<body>
<fieldset id="zone">
<br><br>
<legend><strong>Drop one or more files inside...</strong></legend>
<br><br>
</fieldset>
<script type="text/JavaScript">
// when the whole document has loaded, call the init function
$(document).ready(init);
function init() {
var zone = $('#zone'),
message = $('.message', zone);
// send all dropped files to /upload on the server via POST
zone.filedrop({
paramname: 'file',
maxfiles: 200,
maxfilesize: 20,
url: '/upload',
}
}
</script>
</body>
</html>
參數paramname: 'file'
隨請求以某種方式發送,因此在我的Flask應用程序中,我可以通過以下方式獲取上傳的文件:
@app.route('/upload', methods=['POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
file.save('myfile.ext')
return 'Done'
但是,如何使用FileDrop.js獲取上傳的文件? 我在文檔中看不到如何通過POST傳遞附加參數的可能性。 例如,當我遵循文檔中的最小示例時
<html>
<head>
<script type="text/javascript" src="https://github.com/ProgerXP/FileDrop/blob/master/filedrop.js"></script>
</head>
<body>
<fieldset id="zone">
<legend>Drop a file inside...</legend>
<p>Or click here to <em>Browse</em>...</p>
</fieldset>
<script type="text/JavaScript">
// when the whole document has loaded, call the init function
$(document).ready(init);
function init() {
var options = {iframe: {url: '/upload'}}
var zone = new FileDrop('zone')
// Do something when a user chooses or drops a file:
zone.event('send', function (files) {
// FileList might contain multiple items.
files.each(function (file) {
// Send the file:
file.sendTo('/upload')
})
})
}
</script>
</body>
</html>
然后嘗試檢查Flask中上傳的文件:
@app.route('/uploadtest', methods=['POST'])
def uploadtest():
print(request.files)
return 'end'
request.files
現在是ImmutableMultiDict([])
,我不知道如何從Flask訪問它。 有什么建議么?
我實際上正在處理這個相同的問題,也許可以幫助您解決我所確定的問題。
首先,只有在使用特定編碼和類型從表單發送數據時,燒瓶請求的files
屬性才可用。 FileDrop不使用此屬性,因此請求中的files
屬性應為空。
標簽用enctype = multipart / form-data標記,並以該形式放置。 http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
FileDrop似乎不像dropzone.js使用這種形式那樣發送。 我所做的就是查看FileDrop發出的網絡請求。 這是一個帖子。 我可以看到它是作為帖子處理的。 數據在哪 在我的瀏覽器中的網絡請求中,我可以看到一個名為X-File-Name
的標頭,它是被上傳文件的URL引用名稱。 我可以在請求對象中訪問它。
fileName = urlparse.unquote(request.headers['X-File-Name'])
實際數據在哪里? 它在POST請求的主體中。 那是在request.data
-整個文件,無論采用哪種編碼格式上傳。
foo = open('/tmp/%s' % fileName, 'w')
foo.write(request.data)
foo.close()
這只是一個例子,但是可以。 顯然,您仍應遵循為保護該文件名而鏈接的flask“文件上傳”頁面上的安全性提示,但除此之外,僅此而已。
使用post body的直接缺點是每個請求只有一個文件,但這對於我的特定應用程序來說並不是什么大問題。 希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.