Skip to content

Instantly share code, notes, and snippets.

@cute-angelia
Created March 31, 2022 09:17
Show Gist options
  • Save cute-angelia/2100617f80dce617112f2d917a3b3dc8 to your computer and use it in GitHub Desktop.
Save cute-angelia/2100617f80dce617112f2d917a3b3dc8 to your computer and use it in GitHub Desktop.
文件处理JS
class FileHelper {
FetchToBlob(url, opt = {}) {
return new Promise((reslove, reject) => {
if (!url) {
reject()
return
}
fetch(url, opt).then(function (response) {
if (response.ok) {
reslove(response.blob());
return
}
console.log(response);
reject(response)
return
}).catch(function (error) {
console.log('There has been a problem with your fetch operation: ', error.message);
reject(error)
return
});
})
}
BlobToDataURL(blob) {
return new Promise((reslove) => {
var reader = new FileReader();
reader.onload = function (e) {
reslove(e.target.result)
};
reader.readAsDataURL(blob);
})
}
// https://gist.github.com/fupslot/5015897
DataURIToBlob(dataURI) {
return new Promise((reslove, reject) => {
if (dataURI && dataURI.indexOf(",")) {
// base64 => const base64Str = Buffer.from(str, 'utf8').toString('base64');
// var byteString = atob(dataURI.split(',')[1]);
const byteString = Buffer.from(dataURI.split(',')[1], 'base64').toString('utf8');
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var bb = new Blob([ab]);
reslove({
"blob": bb,
"mime": mimeString,
})
} else {
reject({})
}
})
}
}
export default new FileHelper()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment