javascript 用作文件上传的分区?

qij5mzcb  于 2023-02-02  发布在  Java
关注(0)|答案(3)|浏览(128)

我只是想做一个上传或类似于浏览的div本身,像作为一个文件输入和触发其功能,但我的问题是,我是新的java脚本和相当尴尬自己的头脑 Storm 近一个小时,并寻找同样的问题在互联网上。
所以我别无选择只能在这里问问题
我的代码

<script type="">
    	
    $('#pic1').click(function (Upload) {
     		$('#fileToUpload').click();
    });
    
    </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div id="pic1" style="border:1px solid white;width:200px;height:150px;float:left;margin:10px;" onclick="Upload">
    					<input type="file" name="fileToUpload" id="fileToUpload" size="1" style="display:none;">
    					
    
    				</div>


<br> while my file input is hidden inside the div<br>
8gsdolmq

8gsdolmq1#

$(document).ready(function() {

    
    var readURL = function(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('.profile-pic').attr('src', e.target.result);
            }
    
            reader.readAsDataURL(input.files[0]);
        }
    }
    

    $(".file-upload").on('change', function(){
        readURL(this);
    });
    
    $(".upload-button").on('click', function() {
       $(".file-upload").click();
    });
});
.upload-button {
    padding: 4px;
    border: 1px solid black;
    border-radius: 5px;
    display: block;
    float: left;
}

.profile-pic {
    max-width: 200px;
    max-height: 200px;
    display: block;
}

.file-upload {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="profile-pic" src="http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg" />
<div class="upload-button">Upload Image</div>
<input class="file-upload" type="file" accept="image/*"/>

此代码段专用于像accept="image/*"/这样指定的图像

jslywgbw

jslywgbw2#

您只需将输入放入label中。
尝试以下代码段。

input[type=file] {
  display: none;
}

label {
  border: 1px solid white;
  text-align: center;
  color: #FFF;
  border-radius: 4px;
  margin: auto;
  width: 120px;
  padding: 10px;
  display: block;
  background-color: #0095ff;
  cursor: pointer;
}
<form id="test_form" method="GET" action="">
  <label id="pic1">
    Upload Picture
    <input type="file" name="fileToUpload" id="fileToUpload" size="1" />

  </label>
</form>
blmhpbnm

blmhpbnm3#

<style type="text/css">
#pic1{
    border:1px solid black;
    width:200px;
    height:150px;
}   
</style>

<form action="" method="post" enctype="multipart/form-data">
    <div id="pic1">Upload</div>
    <input type="file" name="fileToUpload" id="fileToUpload" style="display:none;"/>
    <input type="submit" value="submit" name="submit" />
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$('#pic1').click(function(){ 
    $('#fileToUpload').trigger('click'); 
});
</script>

相关问题