1

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.

2
  • 1
    You could google "Ajax file upload" and apply that. Commented Mar 12, 2018 at 10:20
  • @Martijn can you suggest how to access file from assets folder to Component or Service in angular? Commented Mar 12, 2018 at 10:40

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Can you provide some explanation about how it works?
Ok i got it, but how can i create file object with this sanitized url any idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.