flask 上传文件
采用wtf 上传文件
设置表单:
class Up_file_Foem(FlaskForm): body = FileField(u'选择上传文件', validators=[Required()]) submit = SubmitField(u'开始上传')
设置 前端页面
@main.route('/', methods=['GET', 'POST']) # def index(): form = Up_file_Foem() print os.path.dirname(__file__) if form.validate_on_submit(): file = form.body.data # filename = secure_filename(file.filename) #判断文件名合法 但是当遇到中文时会导致文件名只剩后缀 filename = form.body.data.filename file.save(os.path.join(os.path.dirname(__file__), filename))#file是文件流 save(所要保存文件的直接路径) print '文件保存成功' else: print '---------------' return render_template('index.html', form=form)前端页面
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% import "_macros.html" as macros %} {% block title %}首页{% endblock %} {% block page_content %} <div class="page-header"> <h1>欢迎</h1> </div> <div> {{ wtf.quick_form(form) }} </div> {% endblock %} {% block scripts %} {% endblock %}
django 上传文件
html 表单提交
<form enctype="multipart/form-data" method="POST" action="http://10.10.10.242:5000/EasyNode/v1/NODE/conversion_kvm/"> <input type="text" name="a"> <br> <input type="file" name="myfile" /><br> <br /> <input type="submit" value="上传文件" /> </form>
后台获取:
if request.method == 'POST': myFile = request.FILES.get("myfile", None) print request.POST['a'] if os.path.exists(file_path + '/' + myFile.name): # 判断文件是否重名 File_name = time.strftime('%Y_%m_%d', time.localtime(time.time())) + myFile.name else: File_name = myFile.name if not myFile: return HttpResponse(simplejson.dumps({'code': 1,'msg':'name repeat'})) try: destination = open(os.path.join(file_path, File_name), 'wb+') # 保存文件 for chunk in myFile.chunks(): # 分块写入文件 destination.write(chunk) destination.close() except: HttpResponse(simplejson.dumps({'code': 2,'msg':'save file erro'})) return HttpResponse(simplejson.dumps({'code': 0}))