Javascript 如何使图像充当上载文件按钮

Javascript 如何使图像充当上载文件按钮,javascript,jquery,html,css,ajax,Javascript,Jquery,Html,Css,Ajax,我想让一个图像像一个按钮一样,按下它可以让我上传另一个图像 我现在拥有的是代码片段中的部分,但我想让它从我的服务器中拉一个图像作为按钮,然后运行一些ajax,这样就不必重新加载页面,然后显示所选的图像(之前的图像应该更改为所选的图像) .Uploadbtn{ 位置:相对位置; 溢出:隐藏; 填充:10px 20px; 文本转换:大写; 颜色:#fff; 背景:#000066; -webkit边界半径:4px; -moz边界半径:4px; -ms边界半径:4px; -o-边界半径:4px; 边界

我想让一个图像像一个按钮一样,按下它可以让我上传另一个图像

我现在拥有的是代码片段中的部分,但我想让它从我的服务器中拉一个图像作为按钮,然后运行一些ajax,这样就不必重新加载页面,然后显示所选的图像(之前的图像应该更改为所选的图像)

.Uploadbtn{
位置:相对位置;
溢出:隐藏;
填充:10px 20px;
文本转换:大写;
颜色:#fff;
背景:#000066;
-webkit边界半径:4px;
-moz边界半径:4px;
-ms边界半径:4px;
-o-边界半径:4px;
边界半径:4px;
宽度:100px;
文本对齐:居中;
光标:指针;
}
.Uploadbtn.输入上载{
位置:绝对位置;
排名:0;
右:0;
保证金:0;
填充:0;
不透明度:0;
身高:100%;
宽度:100%;
}

形象

这是在HTML表单中使用图像代替按钮的标准方式。

HTML:

<div class='image-upload-btn'></div>
Javascript:

$('.image-upload-btn').on('click', function(){
     var input = document.createElement('INPUT');
     input.type = 'file';
     $('html body').append(input);
     input.click();
})

//after you uploaded new image, you should get an url point to that image,   
//and change the background-image with the new image url
$('.image-upload-btn').css('background-image', 'url(' + newImageUrl + ')');

您只需放置一个图像(将其源设置为图像源)并隐藏文件字段。 每当有人点击图像时,javascript就会触发“点击隐藏文件”字段

然后编写一个javascript方法,当File_字段值更改时调用该方法。 此方法将文件上载到服务器并返回成功消息以及新上载的图像url。将图像源设置为从服务器接收的新上载图像

<style>
.file_field{
display: none;
}
</style>

 <div class="Uploadbtn">
  <input type="file" class="file_field" />
  <img src="/my_awesome_image.jpg" class='image-field'>
</div>

   <script type="text/javascript">
   $('.image-field').click(function(){
   $('.file_field').trigger('click');
})
$('.file_field').change(function(e){
  var files=e.target.files;
  uploadFiles(files,e)});
</script>
function uploadFiles(files,event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
        url: 'submit_image_url?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                $('.image_field').attr("src",data.new_source); #Set the newly source returned from server here. It is expecting the server will return the source url in 'new_source' key
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
}

.file\u字段{
显示:无;
}
$('.image字段')。单击(函数(){
$('.file_field')。触发器('click');
})
$('.file_字段').change(函数(e){
var files=e.target.files;
上传文件(文件,e)};
函数上载文件(文件、事件)
{
event.stopPropagation();//停止事件发生
event.preventDefault();//完全停止工作
//在此处启动加载微调器
//创建formdata对象并添加文件
var data=new FormData();
$.each(文件、函数(键、值)
{
数据。追加(键、值);
});
$.ajax({
url:'提交图片\u url?文件',
键入:“POST”,
数据:数据,
cache:false,
数据类型:“json”,
processData:false,//不处理文件
contentType:false,//将content-type设置为false,因为jQuery将告诉服务器它的查询字符串请求
成功:函数(数据、文本状态、jqXHR)
{
if(typeof data.error==‘未定义’)
{
//Success因此调用函数来处理表单
$('.image_field').attr(“src”,data.new_source);#在此处设置从服务器返回的新源。服务器应在“new_source”键中返回源url
}
其他的
{
//在这里处理错误
console.log('ERRORS:'+data.error);
}
},
错误:函数(jqXHR、textStatus、errorshown)
{
//在这里处理错误
console.log('ERRORS:'+textStatus);
//停止加载旋转器
}
});
}

通过ajax上传详细的文件,请按照帖子进行操作。

OP说“……然后运行一些ajax,不必重新加载页面,然后显示所选的图像”。可能问题太广泛了。建议看一看这个复杂的解决方案:我在这里尝试过,但不会显示图像演示:我修复了它,请参阅更新。我已将代码放在代码段中,如$('.image upload btn')。在('click',function(){var input=document.createElement('input')上;input.type='file';input.style.display='none'$('html body')。追加(输入);input.click();input.onchange=function(){$('.image upload btn').css('background-image','url();}}});.image upload btn{背景图像:url(');背景位置:居中;背景大小:封面;宽度:50px;高度:50px;}只有图像显示,但单击功能没有运行。我似乎找不到这段代码的问题。例如,由于这两部分代码在我的test.php中,没有更多,也没有更少。@MarkoCen
$('.image-upload-btn').on('click', function(){
     var input = document.createElement('INPUT');
     input.type = 'file';
     $('html body').append(input);
     input.click();
})

//after you uploaded new image, you should get an url point to that image,   
//and change the background-image with the new image url
$('.image-upload-btn').css('background-image', 'url(' + newImageUrl + ')');
<style>
.file_field{
display: none;
}
</style>

 <div class="Uploadbtn">
  <input type="file" class="file_field" />
  <img src="/my_awesome_image.jpg" class='image-field'>
</div>

   <script type="text/javascript">
   $('.image-field').click(function(){
   $('.file_field').trigger('click');
})
$('.file_field').change(function(e){
  var files=e.target.files;
  uploadFiles(files,e)});
</script>
function uploadFiles(files,event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
        url: 'submit_image_url?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                $('.image_field').attr("src",data.new_source); #Set the newly source returned from server here. It is expecting the server will return the source url in 'new_source' key
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
}