【发布时间】:2017-08-05 16:30:47
【问题描述】:
我已设法使用 HTML 和 JS 在我的页面上加载图像,但我似乎无法将图像发布到我的 MongoDB 并且它不会显示在我的“主页”页面上。
HTML:
<div class="container">
<h1 style="text-align: center">Post a New Guitar</h1>
<div class="col-md-6">
<form action="/guitars" method="POST">
<div class="input-group">
<label>Item Name</label>
<div class="input-group">
<input class="form-control" type="text" name="name" placeholder="Name">
</div>
<label>Upload Image</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" id="imgInp">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id="img-upload"/>
<div class="input-group">
<button class="btn btn-lg btn-primary btn-block">Submit!</button>
</div>
<a href="/guitars">Go Back</a>
</div>
JS:
$(document).ready( function() {
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [label]);
});
$('.btn-file :file').on('fileselect', function(event, label) {
var input = $(this).parents('.input-group').find(':text'),
log = label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
});
提交表单时,我希望它显示已使用 JS 上传的图像并将其“保存”到我的数据库中。
【问题讨论】:
-
“提交表单时,我希望它显示已使用 JS 上传的图像” 在问题代码中阻止
<form>提交的默认操作在哪里?
标签: javascript html mongodb image-uploading jquery-file-upload