2012-11-02 27 views
1

我有一个文件输入,我已经被定制为一个自定义按钮,但是当用户上传文件时我无法保留上传图像。它被替换为文件名称的文本,但我也想保留图像。我知道这很简单,但似乎无法弄清楚。这里是代码:使用jquery风格的文件输入

HTML:

<div id="file"><img src="~/Images/choosefile.png" /></div> 
<input type="file" name="file"/> 

的Javascript:

var wrapper = $('<div/>').css({ height: 0, width: 0, 'overflow': 'hidden' }); 
var fileInput = $(':file').wrap(wrapper); 

fileInput.change(function() { 
    $this = $(this); 
    $('#file').text($this.val().substring(12, 75)); 
}) 

$('#file').click(function() { 
    fileInput.click(); 
}).show(); 

CSS:

`#file 
{ 
    display:none; 
    cursor: pointer; 
}​` 

**更新 - 这里是事情发展的结果,如果任何人都想使用它* * *

HTML:

<div id="file" style="margin-right:10px;"><img src="~/Images/choosefile.png" style="margin-bottom:-5px; padding-right:10px;"/><span style="border-left-width:10px;"></span></div> 
<input type="file" name="file"/> 

的Javascript:

var wrapper = $('<div/>').css({ height: 0, width: 0, 'overflow': 'hidden' }); 
var fileInput = $(':file').wrap(wrapper); 

fileInput.change(function() { 
    $this = $(this); 
    $('#file>span').text($this.val().substring(12, 75)); 
}) 

$('#file').click(function() { 
    fileInput.click(); 
}).show(); 

CSS:

`#file 
{ 
    display:none; 
    cursor: pointer; 
}​` 

回答

0

当您使用的.text(),它与更换您的图像文件输入的值。我建议在DIV中添加一个span,并设置当前输入的值。这将更容易分开和跟踪。

HTML

<div id="file"><img src="~/Images/choosefile.png" /><span></span></div> 
<input type="file" name="file"/> 

JQuery的

var fileInput = $(':file').wrap(wrapper); 
fileInput.change(function() { 
    $this = $(this); 
    $('#file>span').text($this.val().substring(12, 75)); 
}) 
0
fileInput.change(function() { 
    $this = $(this); 
    $('#file').text($this.val().substring(12, 75)); 
}) 

在这段代码中,你必须改变一些代码:

fileInput.change(function() { 
    $this = $(this); 
     $('#file').html('<img src="'+$this.val()+'" />'); 
}) 

注:确保图像是已经在该你从上传的服务器。