shopnilSS

Upload Single file

Jun 26th, 2021 (edited)
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. //Upload single file with extension filter
  2. const fs = require("fs")
  3.  
  4. const singleImageUploader = (file, extension) => {
  5. let config = {
  6. dataUrl: `http://localhost:3030`, //set the default data url
  7. saveDirectory: `${__dirname}/../../public`, //set the save directory of the data
  8. fileName: `profile`, //set the file name
  9. }
  10.  
  11. const myFile = file //store the file here
  12. const acceptedExtension = extension //store the extension what we accepted
  13. const {base64, size} = myFile //get the data from my data
  14. const dataExtension = base64.split(';')[0].split('/')[1] //get the extension of my data
  15. const myBase64Data = base64.split(';base64,')[1] //get the base 64 data of my data
  16. const myFileName = `${config.fileName}${+new Date()}.${dataExtension}` //set the file new name
  17. const myDataUrl = `${config.dataUrl}/${myFileName}` //set the data new data url
  18.  
  19. //check the file formate is valid or not
  20. const isValidExtension = acceptedExtension.find(val => val == dataExtension)
  21. const saveDirectory = `${config.saveDirectory}/${myFileName}`
  22. if(isValidExtension){
  23. fs.writeFile( saveDirectory , myBase64Data, {encoding: "base64"}, (err) => {
  24. if(err) {
  25. console.log(err);
  26. }else{
  27. console.log("File added successfully");
  28. }
  29. }) //save the data into public folder
  30. return{
  31. fileAddStatus: true,
  32. extensionValidation: true,
  33. fileUrl: myDataUrl
  34. }
  35. }else{
  36. console.log("hello I am from else");
  37. return{
  38. extensionValidation: false,
  39. fileUrl: null,
  40. fileAddStatus: false
  41. }
  42. }
  43. }
  44.  
  45. module.exports = {
  46. singleImageUploader
  47. }
Add Comment
Please, Sign In to add comment