如何在HTML中引用上传的img src

How to reference to an uploaded img src in HTML

本文关键字:img src 引用 HTML      更新时间:2023-09-26

我正在创建一个响应式移动网站,我希望能够从设备上拍摄并上传照片。我已经使用处理了这个部分

<form method="post" action="takephoto.php" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile" accept="image/*;capture=camera"/>
</form>

现在,我遇到的问题是,在我选择了要使用的图片后,我不知道以后如何在代码中引用它。我需要这样做的原因是我使用的是.js库,它允许我上传ISBN条形码的图片,.js文件会读取这个文件,并将ISBN作为文本吐出,我稍后会做更多的处理。(可能将此链接到Google Books API)

这就是我获取条形码扫描仪.js的地方:http://badassjs.com/post/654334959/barcode-scanning-in-javascript

我对这一切还比较陌生,谢谢你的帮助。

您将不得不使用ajax。此链接包含一些有用的信息。

使用ajax上传图片,并在响应中返回url或"失败"。然后你可以在你的js代码中使用

if(response=="failed"){
    //Handle upload failed
}
else {
    //Handle url. Here response is your url actually.
              // So to append the image to a given id, you would use,
    $("#append_to_id").append("<img src='"+response+"'>");
}

由于您使用的JavaScript库正在解析页面上的图像,你必须在上传后在页面上显示图像。

所以基本上你需要4个步骤来实现这一点:

  1. 展示上传表格(这是你在问题中所做的)
  2. 获取步骤1中上传的图像并将其保存到可访问的位置
  3. 在屏幕上显示图像
  4. 调用get_barcode_from_image.js进行解析

这里有一段代码供参考。它包含以上所有4个步骤。

<?php
// step 2: save the image
if ($_FILES['myfile']['error'] == 0) {
    move_uploaded_file($_FILES['myfile']['tmp_name'], 'u/barcode.jpg');
?>
<!-- step 3: show the image -->
<img src="u/barcode.jpg" id="barcode">
<script src="get_barcode_from_image.js"></script>
<div id="result"></div>
<!-- step 4: parse the barcode -->
<button onclick='document.getElementById("result").innerHTML = getBarcodeFromImage("barcode")'>scan</button>
<?php
}
?>
<!-- step 1: show the upload form -->
<form method="post" action="barcode.php" enctype="multipart/form-data">
<input type="hidden" name='a' value='b'/>
<input type="file" id="myfile" name="myfile" accept="image/*;capture=camera"/>
<input type="submit" value="submit" />
</form>

当然,您可以使用ajax来获得更好的用户体验,但过程不会改变。