如何解决我正在使用 jQuery 预览为每个图像添加一个按钮如何操作按钮?
我可以毫无问题地预览许多图像。但是我不知道如何获取上传部分点击的图片的值并用ajax发送?
HTML:
<div>
<input type="file" name="file[]" id="images" multiple />
</div>
<ul id="prewiew">
</ul>
JavaScript:
$(document).ready(function () {
$('#images').on('change',function (e) {
//It prints the added pictures one by one on the page with a loop.
var files = e.target.files;
$.each(files,function (i,file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var template = '<li>' +
'<img src="' + e.target.result + '" width="50" height="50"> ' +
'<label>' + file.name + file.size + '</label> <input type="text" name="title">' +
' <button class="btn btn-sm btn-info upload">Yükle</button>' +
'</li>';
$('#prewiew').append(template);
$('#resim').val('');
};
});
});
$(document).on('click','.upload',function () {
//How can I receive and transfer data when the button is clicked?
var file = $(this).closest('img');
var data = new FormData();
data.append('ImageFile',file);
$.ajax({
url: '/Home/ImagePost/',type: 'POST',data: data,contentType: false,processData: false,success: function () {
},});
});
总结:我正在预览多个图像。我想通过按上传按钮发送预览图片。
解决方法
缺少的部分是 multiprocessing.Manager
对象,发送图像文件时需要该对象。
如果您使用全局引用维护文件数组,那么您将可以在发送时访问必要的文件对象。
唯一需要做的就是将按钮与其对应的 file
对象相关联。
file
然后点击处理程序可以访问相应的 // CHANGE: declare `files` as a global here:
let files;
// end CHANGE
$(document).ready(function () {
$('#images').on('change',function (e) {
//It prints the added pictures one by one on the page with a loop.
files = e.target.files;
$.each(files,function (i,file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
// CHANGE: add a `data-fileindex` attribute to the button
// to associate button with its file object
var template = '<li>' +
'<img src="' + e.target.result + '" width="50" height="50"> ' +
'<label>' + file.name + file.size + '</label> <input type="text" name="title">' +
'<button ' +
' class="btn btn-sm btn-info upload"' +
' data-fileindex="' + i + '">' +
'Yükle</button>' +
'</li>';
// end CHANGE
$("#prewiew").append(template);
$("#resim").val('');
}
});
});
对象:
file
有关如何使用 ajax 上传文件的详细信息,请参阅现有的 How can I upload files asynchronously?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。