我正在使用jquery形式的javascript与python。 我的网站有两种形式,一种用于上传视频,另一种用于上传图像(该视频的预览图片)。 使用下面的代码,如果我首先提交图像然后提交视频,则运行正常,但反之亦然。图片的POST只是像this screenshot
一样保持待定状态代码如下:
HTML
<div class='wrapper span12'>
<div class='span6'>
<h3>Upload video</h1>
<form id='uploadvideoform' action="{{url_for('video.upload_video')}}" method="post" enctype="multipart/form-data">
<input name="myFile" id='myFile' type="file">
<input type='submit' value="Upload">
</form>
<div id="videoresult"></div>
</div>
<div class='span6'>
<h3>Upload thumbnail</h1>
<form id='uploadimgform' action="{{url_for('video.upload_img')}}" method="post" enctype="multipart/form-data">
<input name="imgFile" id='imgFile' type="file">
<input type='submit' value="Upload">
</form>
<div id="imgresult"></div>
</div>
</div>
使用javascript:
<script>
$(document).ready(function (e) {
//ajax upload video
$('#uploadvideoform').ajaxForm({
beforeSubmit: function() {
$('#videoresult').html('Submitting... <img src="/static/img/loading-2.gif" />');
},
success: function(data) {
var preview_str='';
var $out = $('#videoresult');
preview_str += '<video src="http://localhost:5001/static/' + data.video_link +'" controls type="video/mp4" width=480 height=270></video>';
$out.html(preview_str);
$('#url').val(data.video_link);
}
});
//ajax upload img
$('#uploadimgform').ajaxForm({
beforeSubmit: function() {
$('#imgresult').html('Submitting... <img src="/static/img/loading-2.gif" />');
},
success: function(data) {
var preview_str='';
var $out = $('#imgresult');
preview_str += '<img src="http://localhost:5001/static/' + data.img_link +'" width=400 />';
$out.html(preview_str);
$('#imgPath').val(data.img_link);
}
});
});
</script>
服务器端:
@video.route('/upload_video', methods=['GET','POST'])
def upload_video():
if request.method == 'POST':
current_time = datetime.now().strftime("%Y-%m-%d")
savepath = os.path.join(app.config['UPLOAD_VIDEO']) + '\\' + current_time
file = request.files['myFile']
if not os.path.exists(savepath):
os.mkdir(savepath)
savepath = savepath + '\\' + file.filename
file.save(savepath)
flash(_("video uploaded successfully!"), "success")
status = 'success'
video_link = 'video\\'+current_time+'\\'+file.filename
return jsonify(status=status, video_link=video_link)
@video.route('/upload_img', methods=['GET','POST'])
def upload_img():
if request.method == 'POST':
print 'co vo roiiiiiiiiiiiiiiiiiiiii'
savepath = os.path.join(app.config['UPLOAD_VIDEO_THUMBNAIL'])
file = request.files['imgFile']
if not os.path.exists(savepath):
os.mkdir(savepath)
savepath = savepath + '\\' + file.filename
print savepath
file.save(savepath)
print 'save xong'
flash(_("image uploaded successfully!"), "success")
status = 'success'
img_link = 'img\\video\\'+file.filename
return jsonify(status=status, img_link=img_link)