如何在点击图片按钮上传新文件

时间:2013-04-25 08:43:53

标签: javascript jquery html css3

我有一项任务是从点击图片按钮上传新文件。 我的代码是

    <label>File</lable>
    <input type="image" src="http://upload.wikimedia.org/wikipedia/commons/c/ca/Button-Lightblue.svg" width="30px"/>

点击此按钮我想上传一个新文件。我该怎么做? 你可以查看我的代码 Demo

7 个答案:

答案 0 :(得分:40)

您可以添加隐藏文件输入字段,例如:

<input type="image" src="http://upload.wikimedia.org/wikipedia/commons/c/ca/Button-Lightblue.svg" width="30px"/>
<input type="file" id="my_file" style="display: none;" />

并做:

$("input[type='image']").click(function() {
    $("input[id='my_file']").click();
});

演示:: Updated Fiddle

答案 1 :(得分:4)

不需要将<input><img>放在<label>内的javascript,请确保隐藏<input>,如下所示:

   <label for="image">
      <input type="file" name="image" id="image" style="display:none;"/>
      <img src="IMAGE URL"/>
   </label>

答案 2 :(得分:2)

如果您正在寻找跨浏览器兼容的解决方案,您应该查看plupload(http://www.plupload.com)它支持图像按钮以及我记得的内容。

答案 3 :(得分:2)

你使用的是错误的输入,而是使用文件,如果你想按下代码演示中的圆圈,你将需要使用CSS来改变“提交”的样子。这必须采用以下形式:

<form action="upload_file.php" method="post" enctype="multipart/form-data">
  <input type="file" name="myfile"/>
  <input type="submit" class="circle-btn"/>
<form>

我不知道你在服务器端使用的语言是什么(PHP,ASP.NET等),但是你需要创建一个页面(对于php的xample“upload_file.php”)。您可以在Google中轻松找到有关如何创建此类页面的示例,只需复制pasete代码:

PHP中的一个示例:http://www.w3schools.com/php/php_file_upload.asp

希望有所帮助:)

答案 4 :(得分:1)

您可以使用css。

执行此操作

请查看此博客中的第4个答案。

  

How can I customize the browse button?

您可以将图片用作 .button 类的背景图片。

答案 5 :(得分:0)

DemoUser的补充答案,添加.focus()对我有用。

  $("input[type='image']").click(function() {
    $("input[id='my_file']").focus().click();
  });

答案 6 :(得分:0)

不需要javascript。

Just place both <input type="file"> and <img src=""> inside a label.

Eg:
<label>
    <input type="file" style="display:none">
<img src=""> 
</label>

这将正常工作

演示:https://codepen.io/sandeeprana1001/pen/dyPVvJZ

相关问题