This chapter Beijing Happy 8 sell dsluntan.com We introduce the File upload module involved in Flask Web development
Defining background receive processing logic
@app. Route ('/upload ', methods=[' POST ')
Def upload_file ():
if Request.method = = ' POST ':
Check if the POST request has the file part
If ' file ' isn't in Request.files:logger.debug (' No file part ') return jsonify ({' Code ':-1, ' filename ': ', ' msg ': ' No file part '} ' file = request.files[' file '] # If user does not select file, browser also submit a empty PA RT without filename if file.filename = = ": Logger.debug (' No selected file ') return jsonify ({' Code ':-1, ' filename ': ', ' msg ': ' No selected file '} ' else:try:if file and Allowed_file (file.filename): Origin_file_name = file.filename logger.debug (' filename is%s '% origin_file_name) # filename = secure_filename (file.filename) filename = origin_file_name if os.path.exists (U Pload_path): Logger.debug ('%s PATH exist '% Upload_path) pass else: Logger.debug ('%s path not exist, does make dir '% Upload_path) os.makedirs (Upload_path) File.savE (Os.path.join (upload_path, filename)) Logger.debug ('%s save successfully '% filename) retur N jsonify ({' Code ': 0, ' filename ': origin_file_name, ' msg ': '} ') Else:logger.debug ('%s not ' allow Ed '% file.filename) return jsonify ({' Code ':-1, ' filename ': ', ' msg ': ' File not allowed '}) except Exception as E:logger.debug (' upload file Exception:%s '% e) return jsonify ({' Code ':-1, ' filename ') : ', ' msg ': ' Error occurred '}) Else:return jsonify ({' Code ':-1, ' filename ': ', ' msg ': ' Method not allowed '})
Determining File Types
def allowed_file (filename):
Return '. ' in filename and \
Filename.rsplit ('. ', 1) [1].lower () in Allowed_extensions
Front page code
<div class= "Layui-inline" >
<label class= "Layui-form-label" > Uploading Files </label>
<div class= "Layui-input-inline" >
<input type= "text" name= "Attach" id= "Upload_message" lay-verify= "required" autocomplete= "off"
class= "Layui-input" readonly= "ReadOnly" >
</div>
</div>
<div class= "Layui-inline" >
Style= "Display:none;" >
<button type= "button" class= "layui-btn" id= "upload" ><i class= "Layui-icon" ></i> upload file </button >
</div>
Upload button initialization and callback
Layui.use ([' Upload ', ' layer '], function () {
var upload = Layui.upload;
var layer = Layui.layer;
Upload.render ({
Elem: ' #upload '
, url: '/upload '
, accept: ' File '
, exts: ' txt '
, size:2048
, Done:function (res) {
Console.log (RES);
if (Res.code = = = 0) {
Layer.msg (res.filename + ' upload succeeded ');
$ ("#upload_message"). Val (Res.filename);
$ ("#img_delete"). Show ()
} else {
Layer.alert (' upload failed ');
$ ("#upload_message"). Val (' Upload failed! ‘);
}
}
});
})
Of course allow uploads, and should also be allowed to delete files to delete
@app. Route ('/delete ', methods=[' GET ')
Def delete_file ():
if Request.method = = ' GET ':
filename = request.args.get (' filename ')
timestamp = request.args.get (' timestamp ')
Logger.debug (' Delete file:%s, timestamp is%s '% (filename, timestamp))
Try
FullFile = Os.path.join (upload_path, filename)
if Os.path.exists (fullfile): Os.remove (fullfile) logger.debug ("%s removed success Fully "% fullfile) return jsonify ({' Code ': 0, ' msg ': '} ') Else:return jsonify ({' Code ':-1, ' Msg ': ' File not exist '}) except Exception as E:logger.debug ("Delete File error%s"% E) return jsonify ({ ' Code ':-1, ' msg ': ' File deleted error '} ' Else:return jsonify ({' Code ':-1, ' msg ': ' Method not Allowed '})
Delete button initialization and callback processing
function Do_delete () {
var filename = $ ("#upload_message"). Val ();
Layui.use ([' Upload ', ' layer '], function () {
var layer = Layui.layer;
$.ajax ({
URL: '/delete?filename= ' + filename + ' ×tamp= ' + new Date (). GetTime ()
, type: ' GET '
, Success:function (response) {
Console.log (response)
if (Response.code = = 0) {
Layer.msg (' "' + filename + '" Delete succeeded!) ‘);
$ ("#upload_message"). Val (')
$ ("Img_delete"). Hide ()
} else {
Layer.msg (' ' + filename + ') Delete failed! ‘);
}
}
})
})
}
Flask Web Development Beijing Happy 8 sell file Upload