简体   繁体   中英

How to access image from assets folder to javascript object

Hi everyone I've situation while uploading image in Angular project if user doesn't select image then i want to read image from the assets folder and send it to backend . after hours of trial and error. i'm not able to read the image from the asset folder to a JavaScript file object. if anyone knows please guide to me. Thanks in advance.

Things i've tried

  1. I've tried to fetch it using HttpClient in Angular by passing relative path.
  2. I've tried to create file object by passing relative path to File(url) ; constructor with no luck.

please help me.

My problem is to create a file object by accessing the image from asset folder in the angular(4/5) project.

To access your assets from javascript you need to mark your resource as trusted using DomSanitizer :

constructor(sanitizer: DomSanitizer) {
   const sanitizedUrl = sanitizer.bypassSecurityTrustResourceUrl('/assets/<YOUR_IMAGE>');
}

From Angular Security Why :

To systematically block XSS bugs, Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

How to by pass when trusted.

Finally I got the answer it works irrespective of any JavaScript framework.

var blob = null;
var xhr = new XMLHttpRequest(); 
xhr.open("GET", './assets/<FILENAME>'); 
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function() 
{
    blob = xhr.response;//xhr.response is now a blob object
    var file = new File([blob], 'logo.png', {type: 'image/png', lastModified: Date.now()});
    console.log(file);   
}
xhr.send()
}

For More Details:- http://qnimate.com/javascript-create-file-object-from-url/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM