gpt4 book ai didi

javascript - 文件上传/预览,无法更改图像尺寸

转载 作者:行者123 更新时间:2023-11-30 09:21:16 27 4
gpt4 key购买 nike

我正在尝试上传图像并在用户提交之前进行预览,但由于某种原因我无法更改 div 或图像的宽度或高度,并且它会以正常尺寸进行预览。我什至将它设置为 1px x 1px,但它仍然不起作用。

$(function() {
var imagesPreview = function(input, placeToInsertImagePreview) {

if (input.files) {
var filesAmount = input.files.length;

for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();

reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}

reader.readAsDataURL(input.files[i]);
}
}
};

$('#upload-image').on('change', function() {
imagesPreview(this, 'img.image');
});
});
div.img_container {
max-width: 1px;
max-height: 1px;
}
img.image {
width: 1px;
height: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
<input id='upload-image' type='file' name='files[]' multiple>
<input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

最佳答案

您将图像附加到图像中而不是更新其 src:

$(function() {
var imagesPreview = function(input, img) {

if (input.files) {
var filesAmount = input.files.length;

for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();

reader.onload = function(event) {
$(img).attr('src', event.target.result)
}

reader.readAsDataURL(input.files[i]);
}
}

};

$('#upload-image').on('change', function() {
imagesPreview(this, 'img.image');
});
});
img.image {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
<input id='upload-image' type='file' name='files[]' multiple>
<input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

关于javascript - 文件上传/预览,无法更改图像尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51468796/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com