1

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

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;
}​`
4

2 回答 2

0

当您使用 .text() 时,它会将您的图像替换为文件输入的值。我建议在您的 DIV 中添加一个跨度并在其上设置当前输入的值。它会更容易分离和跟踪。

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));
})
于 2012-11-02T14:29:37.920 回答
0
fileInput.change(function () {
    $this = $(this);
    $('#file').text($this.val().substring(12, 75));
})

在此代码中,您必须更改一些代码:

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

注意:确保图像已经在您从中上传的服务器上。

于 2012-11-02T14:42:21.203 回答