我需要从用户输入(从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
获取用户输入并将每个输入附加到文件中?我在if (formKeys != 'image')
这样的formKeys上尝试了一些ifs无济于事,因为它似乎没有识别出键(console.log(formKeys)
)只返回一些输入而不是图像。
那么这个循环将如何运作呢?
- 到目前为止尝试实施@Kaiido方法的进展:
结果是:不可处理的实体:{image: ["The image field is required."]}
当然我在我的控制器中有这个:
'image' => 'required|mimes:jpeg,jpg,png,gif|image|image_size:>=640'
我拥有所有这些代码,它返回带有修改后图像的blob并将其逐步附加到表单中,但是控制器认为图像不存在:
$(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}));
});
}
});
答案 0 :(得分:1)
您可以获取原始的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)
}
});
});
答案 1 :(得分:0)
@ adeneo的答案是正确的,可用时,您应该直接使用FormData的方法来操作它。
但正如OP在评论中所述,所有浏览器都不支持所有这些方法......
所以一个 hackish 解决方法是在调用name
之前删除<input>
的{{1}}属性,因为只有命名输入应该附加到formData
注意:仅在Safari 9.1.3下测试过,我不确定所有浏览器是否都遵守此规则...
new FormData(form)
从那里,您将能够在formData中附加您自己的文件,因为所有实现都支持function noFileFormData(form){
var files = form.querySelectorAll('input[type="file"]');
var names = [];
Array.prototype.forEach.call(files, function(el){
names.push(el.getAttribute('name')); // save their original names
el.removeAttribute('name'); // remove their attribute
});
var formData = new FormData(form); // 'file' input are excluded
names.forEach(function(n, i){
if(name){
files[i].setAttribute('name', n); // restore the attributes
}
});
return formData;
}
。