我正在尝试在 javascript 中插入以下静态文件夹的静态 url,以便它可以正确加载已保存的文件,但我仍然面临错误。
这就是发生的事情。
正常文件位置是http://localhost/static/uploads/filename.ext但使用以下 javascript,它会根据 View ' url_prefix='/media' 获取位置,因此它获取的 url 是 http://localhost/media/static/uploads/filename.ext
下面是代码:
<script>
$(function(){
$('#fileupload').fileupload({
url: 'upload',
dataType: 'json',
add: function (e, data) {
data.submit();
},
success:function(response,status) {
console.log(response.filename);
var filePath = 'static/uploads/' + response.filename;
$('#imgUpload').attr('src',filePath);
$('#filePath').val(filePath);
console.log('success');
},
error:function(error){
console.log(error);
}
});
})
我正在尝试替换,
var filePath = 'static/uploads/' + response.filename;
与
var filePath = {{ url_for('static', filename='/uploads/') }} + response.filename;
但没有成功。原始文件名设置指向蓝图 url_prefix,我想绕过它。
编辑
这是我的观点
@media.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
extension = os.path.splitext(file.filename)[1]
f_name = str(uuid.uuid4()) + extension
file.save(os.path.join(app.config['UPLOAD_FOLDER'], f_name))
return json.dumps({'filename':f_name})
最佳答案
这里有两条路径需要考虑,您需要密切注意您在哪里使用哪条路径:
- 服务器上的绝对文件路径,例如:
/opt/myapp/media/upload/<filename>
,并且 - 客户端上的相对 urlpath,例如:
https://localhost/static/upload/<filename>
您最简单的解决方案可能是简单地返回文件名,而不带任何目录前缀,然后为您使用它的上下文添加适当的目录。
所以在Python中你仍然可以返回'somefile.jpg':
return json.dumps({'filename': f_name})
在 JavaScript 中,您可以通过以下方式引用“/static/uploads/somefile.jpg”:
var filepath = '/static/uploads/' + response.filename;
关于javascript - Flask,在 Javascript 中提供静态文件和/或文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283536/