Estoy tratando de agregar archivos a un archivo de entrada, pero cuando consuelo la transferencia de datos, veo los archivos y cuando accedo a los archivos, básicamente no devuelve nada y puedo ver los archivos cuando los consuelo, los registro antes de acceder a ellos a través de .files.
_dataFiles = new DataTransfer(); var images = document.querySelectorAll("#UpdatePostModal .post-images__child img") images.forEach((img, index) => { var _ImgName = img.currentSrc.split("/").at(-1) // the srcToFile function will return a promise // so we need to call the then method to get the result which is a file srcToFile(img.currentSrc, _ImgName, "image/jpeg").then( function (file) { _dataFiles.items.add(file); } ); }) console.log(_dataFiles) here I can see the files and their length console.log(_dataFiles.files)// but I get nothing length 0 var image_input = $(updateFormLocal).find("#id_images")[0]; console.log(image_input.files) Por cierto, ¿qué estoy haciendo mal aquí? La función srcToFile .
function srcToFile(src, fileName, mimeType) { return (fetch(src) .then(function (res) { return res.arrayBuffer(); }) .then(function (buf) { return new File([buf], fileName, { type: mimeType }); }) ); }Honestamente, no sé muy bien cómo funcionó, pero finalmente obtuve el resultado que buscaba al menos. pero si alguien está dispuesto a explicarme cómo funcionó, sería genial. primero agregué used await / async como sugirió @Gonzalingui, pero agregué archivos dentro del bucle for en lugar de esperar a que terminara. Nuevamente, si alguien puede explicar qué está sucediendo realmente y cómo lo hizo funcionar.
var _dataFiles = new DataTransfer(); var images = document.querySelectorAll("#UpdatePostModal .post-images__child img") var image_input = $(updateFormLocal).find("#id_images")[0]; images.forEach((img, index) => { var _ImgName = img.currentSrc.split("/").at(-1) // the srcToFile function will return a promise // so we need to call the then method to get the result which is a file // var filesArr = srcToFile(img.currentSrc, _ImgName, "image/jpeg") async function test() { var file = await srcToFile2(img.currentSrc, _ImgName, "image/jpeg") _dataFiles.items.add(file) image_input.files = _dataFiles.files console.log(image_input.files) } test(); console.log(image_input.files)})
Y finalmente también cambié la función srcToFile al usuario asíncrono/esperar
async function srcToFile2(src, fileName, mimeType) { const res = await fetch(src) const arr = await res.arrayBuffer() return new File([arr], fileName, { type: mimeType }); }