将浏览的附件链接恢复到文件输入



下面是我的片段,下面发生的事情是,当我单击文本为"浏览附件"的按钮时,输入文件将被触发,然后紧接着选择文件(图像(,然后,它将被呈现为id为"image_container"的图像标签,然后如果单击文本为"Reset"的按钮,则上一个图像url将被恢复到图像容器(#image_conainer(。变量save_src将保存以前的图像源,save_pic变量将保存以前浏览文件的链接,因此当用户单击"重置"时,save_src会放回图像容器src,然后save_pic会放回输入文件。

图像src的恢复正在工作(它恢复了前一个图像(,但前一个浏览文件的恢复不幸地没有工作,它给我带来了这个错误

"Uncaught InvalidStateError:未能在上设置"value"属性"HTMLInputElement":此输入元素接受一个文件名,该文件名可能只能通过编程方式设置为空字符串。">

有什么想法吗?

附言:这是一个ajax上传图片,所以我采用了某种方便的上传风格。

var save_src, save_pic;
$(document).ready(function(){ 
  $("#reset_button").click(function(){
       $("#employee_image_sidebar").prop("src", save_src);
       $("#browse_file").val(save_pic);
    });
  
  $("#browse_file").change(function(){
        if($(this).val() !== ""){
            save_src = $("#image_container").attr("src");
            save_pic = $("#browse_file").val();
          
            var reader = new FileReader();
            reader.onloadend = function() {
              $("#image_container").prop("src", reader.result);
            }
            if (this.files && this.files[0]) {
              reader.readAsDataURL(this.files[0]);
            } else {
              $("#image_container").prop("src", "");
            }
            
        }
    });
  $("#browse_button").click(function(){
       $("#browse_file").trigger("click"); 
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExAUFBIVFBYZGBMTEQ8QEBYXFBcXGBUUGBQYHSghGBolHBUUITEiJykrLi4uGB8zODMsNygtLisBCgoKDg0OGxAQGzQkHyQsLCwsLCwsLDUsLCwsLCwsLCwsLCwrLCwsLCwsLDUsLCwrLCssLDQsLCwsLCwsLCwsK//AABEIAOEA4QMBIgACEQEDEQH/xAAbAAEBAAMBAQEAAAAAAAAAAAAABgMEBQIBB//EAD0QAAIBAQU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8cCepXRWesVFb5SS8NfA3aNyxXSm5cI+6u95nTAHijSjFYRiorh9XtPYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/9k=" id="image_container"/>
<button id="browse_button">Browse for attachment</button>
<button id="reset_button">Reset</button>
<input type="file" id="browse_file" style="display: none;"/>

由于安全限制,您想做的事情是不可能的。错误消息非常不言自明;除了清除<input type="file">元素之外,没有其他方法可以通过编程设置它的值。只有浏览器用户可以使用浏览器的文件选择器对话框更改它。删除有问题的行,一切都会好起来:

$("#browse_file").val(save_pic); // XXX DELETE THIS

最新更新