flask +layUI+ ajax 上传图片-放到本地文件夹中 记录: 1、在使用layui时出现的问题,加载css,js出现问题 GET http://127.0.0.1:5000/layui/css/layui.css net::ERR_ABORTED 404 (NOT FOUND) 然后我将layui文件夹放到static里改成< link rel=“stylesheet” href=“…/static/layui/css/layui.css” media=“all”>,就行了(好像对于layui文件相对位置的加载,以当前的html位置为基准)
2、使用ajax时 忘记加载 jquery < script src=“…/static/js/jquery-1.10.1.min.js”> </ script> 3、url错误导致一直404 url: “…/user/upload”, 4、UPLOAD_FOLDER = ‘./utils/uploads’ #文件存放路径—不能忘了./ 表示当前项目位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="../static/layui/css/layui.css" media="all">
<script src="../static/layui/layui.js" type="text/javascript" charset="UTF-8"></script>
</head>
<body>
<div>
<input type="file" name="FileUpload" id="FileUpload">
<a class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</a>
</div>
<script src="../static/js/jquery-1.10.1.min.js"></script>
<script type="text/jscript">
$(function () {
$("#btn_uploadimg").click(function () {
var fileObj = document.getElementById("FileUpload").files[0];
if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
alert("请选择图片");
return;
}
var formFile = new FormData();
formFile.append("action", "UploadVMKImagePath");
formFile.append("file", fileObj);
var form_data = formFile;
console.log(form_data);
$.ajax({
url: "../user/upload",
data: form_data,
type: "post",
dataType: "json",
cache: false,
processData: false,
contentType: false,
success: function (result) {
alert("上传完成!");
},
})
})
})
</script>
</body>
</html>
UPLOAD_FOLDER = './utils/uploads'
ALLOWED_EXTENSIONS = set(['jpeg'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
@user_blueprint.route('/upload/', methods=['GET', 'POST'])
@is_login
def upload():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
print("file",file)
filename = file.filename
print("file_name", filename)
from manage import app
print("path", app.config['UPLOAD_FOLDER'])
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return '{"filename":"%s"}' % filename
return ''
参考Ajax+Python flask实现上传文件功能
|