【发布时间】:2018-12-04 04:22:26
【问题描述】:
我有这个 HTML 页面,其中您有一个默认图像,如果您单击“浏览”按钮,图像将更改为您选择打开的那个。现在选择的图像显示在 HTML 中,但它仍然必须保存在“/images”项目文件夹中。
到目前为止,这是我的代码。我已经研究了几天,到目前为止我尝试过的一切都没有奏效。另外,我是 HTML 和 js 的新手,如果有任何初学者的错误,请见谅。关于我需要添加到 js 代码中的任何想法?
html:
<div class="cc-profile-image"><a href="#"><img src="images/photo.png" alt="Image"/></a></div><!--ORIGINAL PHOTO-->
<form action="images/photo.png" onchange="previewFile()" >
Select image to upload:
<input type="file" name="file" id="file" value>
<label for="file"> Select a file to upload</label>
<input type="submit" value="Subir">
</form>
js:
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
//preview.height = "512";
//preview.width = "512";
var file = document.querySelector('input[type=file]').files[0]; //sames as here
//file.height = "512";
//file.width = "512";
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
PS:我没有使用任何数据库,我只是想将上传的照片存储到/images。
【问题讨论】:
-
你有一个服务器在运行,还是你只是在编辑一个 HTML 文件和一个 JS 文件?
-
我将 github 存储库链接到 heroku,因此我可以拥有该项目的实时版本。那将是一个正在运行的服务器,对吧?
-
是的!如果您的浏览器显示
http://...或https://...,那么您正在从正在运行的服务器查看您的页面;如果它显示file://...,那么你没有(即你双击了.html文件)。在这种情况下 zetawars 是权利,您需要一些服务器端代码。 -
注意
action="images/photo.png"现在无效;action应该是提交表单时将调用的服务器端代码的路径。该代码将获得表单数据(在本例中为新图像)。
标签: javascript html image-uploading