gpt4 book ai didi

javascript - 使用输入数据减去文件类型创建新的 formData

转载 作者:行者123 更新时间:2023-12-03 04:13:33 27 4
gpt4 key购买 nike

我需要根据用户输入(从 html 表单发送)创建一个 formData,因为我需要修改图像图片(压缩/调整大小/裁剪),然后将新的 FormData 提交到服务器:

    $(document).ready(function () {

$("#AddModel").on("submit", function (e) {

e.preventDefault();

var formData = new FormData(this);
var formKeys = formData.keys();
var formEntries = formData.entries();

var processedForm = new FormData();

// some loop to insert in processedForm all the entries
// less the file type

// get the file type (image), process it with canvas and append
// to the processedForm

//submit the form

$.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
data: processedForm,
success: function (data) {

console.log(data)

},

});
});

我知道如何修改图像,然后附加到processedForm,但是如何创建processedForm获取用户输入并将每个输入附加到其中,但文件除外?我在 formKeys 上尝试了一些 if,例如 if (formKeys != 'image') 但无济于事,因为它似乎无法识别该 key (console.log(formKeys) )仅返回一些输入而不是图像。那么这个循环如何工作呢?

-- 到目前为止尝试实现 @Kaiido 方法的进展:

结果是:无法处理的实体:{image: ["图像字段为必填项。"]}

当然我的 Controller 中有这个:

'image' => 'required|mimes:jpeg,jpg,png,gif|image|image_size:>=640'

我有所有这些代码,它们返回一个带有修改后的图像的 Blob ,并理论上将其附加到表单中,但是 Controller 认为图像不存在:

$(document).ready(function () {

$("#AddModel").on("submit", function (e) {
e.preventDefault();

var form = $(this);

var inputs = $(this).find('[name]'),

formData = new FormData();


inputs.each(function (index, element) {
if (element.type === 'file') {

var file = element.files[0];


if (file.type.match('image.*')) {

console.log("it's an image");

}

var reader = new FileReader();

reader.readAsDataURL(file);

reader.onloadend = function () {

var base64img = this.result;

var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(this.result));
var srcOrientation = exif.Orientation;

resetOrientationResizeCompress(base64img, srcOrientation).then((img)=> {

console.log(img);

dataURItoBlob(img).then((ia)=> {

console.log(ia);

console.log(element.name);

formData.append(element.name, ia);

});

});

}


} else {

formData.append(element.name, element.value);
}

});


$.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
data: formData,
success: function (data) {

console.log(data)

}
});
});

//该函数处理原始图像

function resetOrientationResizeCompress(srcBase64, srcOrientation) {
return new Promise(function (resolve) {

var img = new Image();

img.onload = function () {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");

var MAX_WIDTH = 1000;
var MAX_HEIGHT = 1000;

// set proper canvas dimensions before transform & export
if ([5, 6, 7, 8].indexOf(srcOrientation) > -1) {
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = height;
canvas.height = width;
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
canvas.width = width;
canvas.height = height;
}

// transform context before drawing image
switch (srcOrientation) {
case 2:
ctx.transform(-1, 0, 0, 1, width, 0);
break;
case 3:
ctx.transform(-1, 0, 0, -1, width, height);
break;
case 4:
ctx.transform(1, 0, 0, -1, 0, height);
break;
case 5:
ctx.transform(0, 1, 1, 0, 0, 0);
break;
case 6:
ctx.transform(0, 1, -1, 0, height, 0);
break;
case 7:
ctx.transform(0, -1, -1, 0, height, width);
break;
case 8:
ctx.transform(0, -1, 1, 0, 0, width);
break;
default:
ctx.transform(1, 0, 0, 1, 0, 0);
}

// draw image
ctx.drawImage(img, 0, 0, width, height);

// export base64
resolve(canvas.toDataURL("image/jpeg", 0.6));
};

img.src = srcBase64;

})

};

//这个将base64转换为数组缓冲区

   function base64ToArrayBuffer(base64) {

//base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
base64 = base64.replace(/^data:([^;]+);base64,/gmi, '');
var binaryString = window.atob(base64);
var len = binaryString.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}

//这个将 dataURItoBlob 转换(也许我可以直接转换 canvas.toBlob() 但我没有在该方法中获得回调参数。

 function dataURItoBlob(dataURI) {

return new Promise(function (resolve) {

// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);

// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}

resolve(new Blob([ia], {type: mimeString}));

});
}
});

最佳答案

您可以获取原始的formdata对象,然后为文件输入设置一个新值,添加更改后的图像等。

您还可以使用formData.delete()删除图像,然后将图像设置为新值

$("#AddModel").on("submit", function(e) {

e.preventDefault();

var formData = new FormData(this);
var image = $('[name=image_input]').get(0).files[0]; // etc

// change image here

formData.set('image_input', changed_image_file);

$.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
data: formData,
success: function(data) {

console.log(data)

},

});
});

如果浏览器支持是一个问题,您可以手动迭代表单输入并将它们附加到 formData 对象

$("#AddModel").on("submit", function(e) {
e.preventDefault();

var inputs = $(this).find('[name]'),
formData = new FormData();

inputs.each(function(index, element) {
if ( element.type === 'file' ) {
var file = element.files[0];
var changed_file = change(file);

formData.append(element.name, changed_file);

} else {
formData.append(element.name, element.value);
}

});

$.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
data: formData,
success: function(data) {

console.log(data)

}
});
});

关于javascript - 使用输入数据减去文件类型创建新的 formData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239064/

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