import * as qs from "https://cdn.skypack.dev/qs@6.10.3";
import * as lodash from "https://cdn.skypack.dev/lodash@4.17.21";
const parts = [
new Blob(['you construct a file...'], {
type: 'text/plain'
}),
' Same way as you do with blob',
new Uint16Array([33])
];
const file = new File(parts, 'sample.txt', {
lastModified: new Date(2020, 1, 1),
type: "text/plain"
});
let data = {
a : file,
b:{
a:"1+2",
b:2,
c:[4,5,6],
d:{
a:1,
b:[1,2,3]
}
}
}
console.log('original data ', data )
let postData = checkHasFile(data)
if( postData instanceof FormData){
for(var pair of postData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
}
function checkHasFile(data) {
const files = new Map()
const queryString = qs.stringify(data, {
arrayFormat: 'brackets',
//indices or bracket
encode: false,
filter: (name, value) => {
if (value instanceof File) {
let id = lodash.uniqueId('__FILE__.')
files.set(id, value)
return id
} else {
return value
}
}
})
console.log( queryString )
if (queryString.includes('__FILE__')) {
// console.log('has file')
data = lodash.split(queryString, '&').reduce((formData, currentValue) => {
const [key, oldValue] = lodash.split(currentValue, '=')
let value = oldValue
if (value.includes('__FILE__')) {
value = files.get(oldValue)
}
formData.append(key, value)
return formData
}, new FormData())
}
return data
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.