您的位置:首页 > Web前端 > JQuery

JQuery+AJAX file upload demo (Python+flask as web server)

2016-03-02 21:27 555 查看
HTML code:

<form id="moment-pane-upload-form" enctype="multipart/form-data">
<input id="moment-pane-file-btn" type="file" name="image" style="display:none" multiple>
</form>


JS code:

var data=new FormData()
data.append('image',$("#moment-pane-file-btn")[0].files[0])

$.ajax({
url:"/upload",
type:'POST',
data:new FormData($("#moment-pane-upload-form")[0]),
cache:false,
processData:false,
contentType:false,
error:function(){
console.log("upload error")
},
success:function(data){
console.log(data)
console.log("upload success")
}
})


new FormData($(“#moment-pane-upload-form”)[0]) can be replaced by data constructed by

data.append(‘image’,$(“#moment-pane-file-btn”)[0].files[0])

be careful of $(“#moment-pane-upload-form”)[0] and $(“#moment-pane-file-btn”)[0].files[0]

@app.route('/upload',methods=['POST'])
def upload():
file=request.files['image']
filename=file.filename.split('.')[0]+'_new.'+file.filename.split('.')[-1]
path=app.config['UPLOAD_FOLDER']+'/'+filename
print file.filename,filename,path
file.save(path)
print 'GET=',file.filename
print 'UPLOAD=',filename,'#'*50
return jsonify({"path":path})

@app.route('/download/<filename>')
def download(filename):
print 'DOWNLOAD=',filename,'*'*50
return send_from_directory(app.config['UPLOAD_FOLDER'],filename)

if __name__=='__main__':
app.run(host='192.168.16.163',debug=True)


HTTP ERROR 500 may occurred, we need to set data=request.get_json(force=True), which ignore the MIME type and take everything as json . Why?I have set the contentType and dataType already.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: