Javascript Fetch: How to fix downloaded blob with weird background colours? - blob

I regularly download images as blob and show them in the html or download the to the HD. Most of the time they show correctly. But sometimes they are loaded for 50% or with weird background colours. Like these examples (last one is normal).
Here is how I download the images. I use the aurelia-fetch-client in the aurelia framework for this.
Html:
<div css="background-image: url(${ imageUrl })"></div>
Javascript:
const blob = await this.client.fetch(`${this.endpoint}/attachments/${this.attachment.name}`,
{
method: 'GET'
}).then((x) => x.blob());
this.imageUrl = URL.createObjectURL(blob);
Any idea what is causing this? It happens randomly to images that I show in the webbrowser or download to the HD. Any help is appreciated.

Related

How can I fadeout my preloader after all contents of my website (including images, videos etc.) has been loaded?

I want to use a preloader animation for my website and want it to fadeout after my site's all content has loaded. I have tried this
way:
<script>
window.onload = function () {
document.querySelector(".loader-container").style.display = 'none';
};
</script>
But sometimes the animation is going infinitely and i can't see any content of my website and sometimes it vanishes before the images had
loaded.I have searched google for various alternatives but none worked.
It will be a great help if anyone could help a beginner like me(it has been 3 months) by providing a code snippet to accomplish this.

Uploading image [Cypress]

I'm trying to upload a jpeg image from local files to a webpage developed here in my job. The thing is, we need to click on the page to open the file explorer and then select the image (or drag and drop into the same spot that may be clicked).
Here is a picture from the web page
I don't know how could i do that, i was trying some code that i've seen in "https://medium.com/#chrisbautistaaa/adding-image-fixtures-in-cypress-a88787daac9c". But don't worked. I actually don't know how it works exactly, could anyone help me?
Here is my code
After #brendan's help, I was able to solve the problem by finding an input that was "hidden" under an element. However, before that I tried drag-n-drop, and cypress returned me an error (despite the successful upload). The context was, immediately after the upload, the element re-renders and cypress told me that:
.
Beside the success with input element, i was wondering how it would be possible to resolve this error, is it possible to do something internally to cypress to ignore or wait until the element re-renders back to normal?
Solutions suggested by cypress:
We're doing this using cypress-file-upload
Here's an example from our code:
cy.fixture(fileName).then(fileContent => {
cy.get(selectors.dropZoneInput).upload(
{ fileContent, fileName, mimeType: "application/pdf" },
{ subjectType: "drag-n-drop" }
);
});
For your purpose, I think this will work:
cy.fixture(imagePath).then(fileContent => {
cy.get(".upload-box").first().upload(
{ fileContent, fileName, mimeType: "image/jpeg" },
{ subjectType: "drag-n-drop" }
);
});

Not able to open PDF url using DocumentViewer ionic 4

I have a pdf URL and I want to open it using DocumentViewer. When I run code:
this._document.viewDocument(pdfUrl, 'application/pdf', options);
It is not opening PDF. I tried downloading PDF to my mobile and then open it. Please find code below:
transfer.download(downloadUrl, filename).then(entry => {
const url = entry.toURL();
if (this._plt.is('ios')) {
this._document.viewDocument(pdfUrl, 'application/pdf', options);
} else {
this._fileOpener.open(pdfUrl, 'application/pdf')
.then(() => console.log('File is opened'))
.catch(e => this.presentAlert('Error opening file', e));
}
});
I have tables and images in my PDF. When I ran above code I am not able to see HTML5 tables in the PDF.
I need help on how to open up PDF URL directly using DocumentViewer.
NOTE: I have seen a couple of post on StackOverflow suggesting to use InAppBrowser. I have a requirement where I need to display it as PDF.
I have read in https://github.com/sitewaerts/cordova-plugin-document-viewer,
that in android : Due to license restrictions in muPDF, the plugin dispatches to a separate (free) viewer app based on muPDF. If the viewer app is not yet installed, the user may be redirected to the google play app store.
https://play.google.com/store/apps/details?id=de.sitewaerts.cleverdox.viewer.
you may use other pdf plugins like
https://github.com/vadimdez/ng2-pdf-viewer/
hope this helps

Image require() in nuxt with hot reload by HRM webpack

I use the dynamic source for vue-webpack images in nuxt :src="require('path/to/image' + dynamic.variable)" in my project navbar. If the users substitute their image through a form which refetches their information and deletes their previous image I get a webpack error module (img) not found (it does not find the new one): is there a way to solve this, like wait for webpack HRM to finish?
I tried setting up a setTimeout() of one second before user re-fetch and it works, but I don't like a random waiting, I'd use a promise or a sync dynamic, the point is webpack hot reload is not controlled by my functions.. I also tried with setting the dynamic path as a computed: but it doesn't fix.
My image tag:
<img v-if="this.$auth.user.image" class="userlogo m-2 rounded-circle" :src="require('#assets/images/users/' + this.$auth.user.image)" alt="usrimg">
My Useredit page methods:
...
methods: {
userEdit() {
//uploads the image
if (this.formImageFilename.name) {
let formImageData = new FormData()
formImageData.append('file', this.formImageFilename)
axios.post('/db/userimage', formImageData, { headers: { 'Content-Type': 'multipart/form-data' } })
// once it has uploaded the new image, it deletes the old one
.then(res=>{this.deleteOldImage()})
.catch(err=>{console.log(err)})
}else{
this.userUpdate() //if no new image has to be inserted, it proceeds to update the user information
}
},
deleteOldImage(){
if(this.$auth.user.image){axios.delete('/db/userimage', {data: {delimage: this.$auth.user.image}} )}
console.log(this.$auth.user.image + ' deleted')
this.userUpdate() // it has deleted the old image so it proceeds to update the user information
},
userUpdate(){
axios.put(
'/db/user', {
id: this.id,
name: this.formName,
surname: this.formSurname,
email: this.formEmail,
password: this.formPassword,
image: this.formImageFilename.name,
})
.then(() => { console.log('User updated'); this.userReload()}) // reloads the updated user information
.catch(err => {console.log(err)} )
},
userReload(){
console.log('User reloading..')
this.$auth.fetchUser()
.then(() => { console.log('User reloaded')})
.catch(err => {console.log(err)} )
},
}
...
the problem happens after "console.log('User reloading..')" and before "console.log('User reloaded');", it is not related to the file upload nor the server response. I broke a single function in many little ones just to check the function progression and its asynchronous dynamics but the only one that is not manageable is the webpack hot reload :/
I'd like the users to upload their images and see their logo in the Navbar appear updated after submitting the form.
First of all, as somebody told you in the comments, webpack hmr shouldn't be used for production.
In Nuxt, everything that you reference from the assets folder will be optimized and bundled into the project package. So the ideal use case for this folder is all assets that can be packaged and optimized, and most likely won't change like fonts, css, background images, icons, etc.
Then, require is called only once by webpack when it is either building the site for local development or building the site for generating a production package. The problem in your case is that you delete the original file while you're in development and webpack tries to read it and fails.
In the case of these images that the user uploads, I think you should use the static folder instead and instead of using require you'll have to change the :src with
:src="'/images/users/' + this.$auth.user.image"
Let me know if this helps.
Okay, I probably solved it.
HMR: you are of course right. Thank you for pointing out, I am sorry, I am a beginner and I try to understand stuff along the way.
Aldarund, thank you, your idea of not changing the path and cache it client side.. I am too noob to understand how I could implement it ( :) ) but it gave me a good hint: the solution was to keep the image name as the user id + the '.png' extension and to manage the image with jimp so that the image name, extension and file type are always the same, and with or without webpack compiling the new path, I always have the correct require().
Jair, thank you for the help, I didn't follow that road, but I will keep it as a second chance if my way creates errors. Just to be specific: the error comes when it does not find -and asks for the name of- the NEW image, not the OLD one, as I wrote in my question: it happens because the fetchUser() functions reloads the user information including the new image name.
Do you guys see any future problems in my methodology?
Really thank you for your answers. I am learning alone and it's great to receive support.

Show a loader while a Meteor CollectionFS and S3 image downloads?

Is there any function/hook for showing a loader while an Amazon S3 image downloads from Amazon S3 (or any image from anywhere for that matter)? I'm not currently using any CDNs or CloudFront, so my downloads can sometimes be slow. I'd like to just show a loader while the image is downloading. In my code I have:
{{#if uploadedCustomLogo}}
{{#with customLogo}}
{{#if isUploaded}}
<div class="img-wrapper">
<img src="{{this.url store='logos'}}" alt=""/>
</div>
{{else}}
{{> loading}}
{{/if}}
{{/with}}
{{/if}}
The issue is the uploading {{> loading }} loader-template runs fine, but it only lasts a fraction of a second because the actual upload is really fast. It's the download that can then take several seconds (sometimes up to twenty or so even on a small image). Is there any way to test/check if an image has been downloaded?
I used FF Inspector to see if there was a delay in the src getting set on the img tag but it gets set immediately. So the wait is really on S3... nothing changes in the DOM once it finally loads.
I'm using CollectionFS and the S3 adapter (Meteor-cfs-s3).
I figured it out. I was searching for the wrong thing on Google. The question is really how to use JQuery to listen for when an image has loaded. So you can just add your loader in your template, then hide it once the load event fires on the image. This simple code works great in Meteor:
Template.myTemplate.events({
'load #whateverImage': function(event) {
event.preventDefault();
// Hide your loader DIV (for example)
hideLoader();
},
The solution is to use has stored helper, I also had a problem figuring this one out isUploaded is to the meteor server but if you want to wait to for it to be uploaded to amazon s3 {{#if this.hasStored 'thumbs'}}
edit:
Here is my custom helper to check if it's upload & stored to amazon s3 (So I can safely create an amazon s3 url and display it to the user).
Which in my case looks like this:
uploadDoc: function () {
var fileId = Template.instance().posterData.get('fileId'); // You can ignore this, It's just how I get the file document id.
if (fileId)
return Images.findOne(fileId); // We need the file document
}
isUploadedAndStored: function (storage) {
if (this && this.copies && this.copies[storage])
return true;
}
sUrl: function () {
if (this && this.copies && this.copies.thumbs)
return 'https://s3-us-west-2.amazonaws.com/NAME/' + this.copies.thumbs.key;
}
using it like this:
{{#with uploadDoc}}
{{#if isUploadedAndStored 'thumbs'}}
<img class="attachment-thumbnail" src="{{sUrl}}">
{{else}}
{{>loading}}
{{/if}}
{{/with}}
How it works? When we subscribe to the uploaded file collection the document will not have copies and when it comes from the server it means it's actually saved on amazon s3, the this.hasStored does similar check but I found it to re-run too many times maybe need to report it to github so they can fix it.