react native dynamic import image from folder containing many files - javascript

I have a image folder say answers where I am storing answer for my question which are images
There are 200 images for now in that folder.
Now I want to show the image of the answer according to the user's answer.
I am generating the answers randomly
`var answer = getAnswers(data)` // some calculation for file name for answer
<Image source={require('../path/to/my/answer/' + answer + '.jpg')}
Doing this I am getting error ``requireexpect exactly 1 string literal argument
I came to know that builder needs to know the location before building.
But how to solve this type of issue.
I can not map 200 files initailly for require
var one = require('../path/one.jpg')
var two = require('../path/two.jpg')
How can I solve this type of issue. Is there any way to do this ??
Help needed.

A dynamic search path in require is simply not possible.
From what I understand you have 2 options here:
1. Generate an Image file
Instead of writing 200 lines by hand you can make a script that scans through your image folder and generates a list of image urls. I would suggest a format similar to:
// Images.js
export const Answers = {
ANSWER_ONE : require('../path/one.jpg'),
ANSWER_TWO : require('../path/two.jpg'),
...
}
Then use it:
import {Answers} from './Images'
var answer = getAnswers(data)
<Image source={Answers[answer]} />
2. Copy image files to asset folders
If choosing this option you have to copy all image files to both your android and ios projects assets folder. You are then able to use them like this:
var answer = getAnswers(data)
<Image source={{uri: '../path/to/my/answer/' + answer + '}} />
Read more about using image assets.
...
Even though the second option seems tempting I would prefer the first in most cases. Mostly because the second requires you to make two copies every time you add an image (assuming you supporting both android and ios). Also, option 1 gives your better typing suggestions where you won't misspell the image name.
Hope this helps!

Related

How to enforce file size limit in jquery.fileupload

I'm using jquery.fileupload() to upload files from a browser to a Node.js server, which parses the files with the "multiparty" npm. I need to enforce a size limit on each file, and also on total size of all the files being uploaded in one request.
The "multiparty" npm allows me to do the latter, but not the former. And even for the latter, the limit isn't enforced until the browser uploads enough data to hit the limit. So the user can wait a long time only to get an error message.
I'd like to enforce the limit on the client-side. I've searched the Internet for solutions, but none of them seem to work. They may have worked in the past, but not with the newest version of Chrome.
I've found that I can determine that the files are too big by watching for a "change" event on the file-input element, like this:
$('#file-input-id').on('change', function() {
console.log(this.files);
});
When this event triggers, this.files contains an array of selected files, including the name and size of each. So I can determine that the caps have been exceeded, and I can alert the user. But I don't know how to stop the files from uploading anyway. Various source on the Internet suggest that I can do this by returning false or manipulating this.files. But none of this seems to work.
I'm testing this against the latest version of Chrome (66.0.3359.139), but I'd like a solution that works with any modern browser.
The file object that exists on the element has a size property which you can use to compare and make validations on the client. I wrote an example in javascript. I know you want it in JQuery but, that was kind of already answered here
Anyways, this is what I came up with ...
var inputElement = document.getElementById("file")
inputElement.addEventListener('change', function(){
var fileLimit = 100; // could be whatever you want
var files = inputElement.files;
var fileSize = files[0].size; //inputElement.files is always an array
var fileSizeInKB = (fileSize/1024); // this would be in kilobytes defaults to bytes
if(fileSizeInKB < fileLimit){
console.log("file go for launch")
// add file to server here
} else {
console.log("file too big")
// do not pass go, do not add to server. Pass error to user
document.getElementById("error").innerHTML = "your file is over 100 KB "
}
})
(CodePen https://codepen.io/HappinessFactory/pen/yjggbq)
Hope that answers your question. Good luck!
Thanks! I'm sure your answer would work if I weren't using jquery.fileupload(), but jquery.fileupload() starts the upload automatically. So there's no "add file to server" logic to perform/skip.
But your answer sent me off in the right direction. For anyone else stuck on this: The trick is to use the "start" or "submit" properties of the "options" object passed into jquery.fileupload(). Both of these are functions, and if either one returns false, the upload is cancelled.

How to capture broken image urls with javascript then pass the urls to php?

I have a site that displays a lot of external images and thumbnails etc, easily up to 100 on a single page. I crawl and index the urls to the images and save them in mysql and display them with this code inside simple loops from queries.
<img src="<?php echo $row['img_url']; ?>" onerror="this.onerror=null;this.src='http://example.com/image.jpg';" width="150" height="150">
I use that particular code to replace any broken image urls with a default image.
My question is, is it possible to use javascripts onerror or something else to capture the image url that is broken when a broken url is found so that I can pass the url back to php and be able to automatically delete the urls from my database?
I am not very good with javascript and after searching I can't seem to find anything similar to what I am looking for, I mostly just find lots of posts on how to replace the broken image.
I am open to any ideas really, the original image urls come from $row['img_url'] as you can see in the code but I know I need javascript or something to catch the errors and then somehow get the urls passed back to php so that I can automate the deletion process instead of just replacing images with default images like my currnt code.
you can use file_exists to check like so:
if(file_exists($row['img_url'])){
echo '<img src="'.$row['img_url'].'" onerror="this.onerror=null;this.src="http://example.com/image.jpg";" width="150" height="150">';
}
You are almost there. Simply replace this:
this.src='http://example.com/image.jpg'
with:
this.src='http://example.com/image-missing.php?url={$row['primaryKey']}&w=150&h=150'
Now, "image-missing.php" receives the URL of the missing file and the intended size of the missing image. What it needs to do is clean the database (after checking that the call is legitimate (1) and that the referred row exists(2)), and output a replacement image in the proper size.
(1) otherwise you have just handed the possibility of deleting your whole image database to the first guy with time on his hands.
(2) someone else might have loaded the same page, and called the same script one millisecond ago.
You should try something like this (example uses vanilla JS, no jquery or any 3rd party library):
var allImages = document.querySelectorAll('img');
for (var i = 0; i < deleteLink.length; i++) {
document.querySelector('img').addEventListener('error', function(e) {
// Delete a user
var url = "<DELETION_URL>";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'?resource=' + e.target.src, true);
});
}
<DELETION-URL> should point to a PHP script that accepts DELETE (or at least POST) requests and read the resource parameter. It will then remove the image provided that resource is truly missing.

Getting image dimensions with Angular vs Node.js

I am confused about the best way to discover the image dimensions, or the naturalWidth of images, given the url to the image, most often found in the src attribute of an <img> tag.
My goal is take as input a url to a news article and use machine learning to find the top 5 biggest pictures (.jpg, .png, etc) files in the document. The problem with using the front-end to do this, is that I don't know of a way to use AJAX to http GET html from some random page of some random server, because of CORS related issues.
However, using Node.js, or some server technology, I can make requests to get the HTML from other servers (as one would expect) but I don't know a way of getting the image sizes without downloading the images first. The problem is that, I want the downloaded images on the front-end, not the back-end, and therefore downloading images with Node.js is wasted effort, if it's just to check the image dimensions.
Has anyone experienced this exact problem before? Not sure how to proceed. As I said, my goals are to download images on the front-end, and keep the ones that are bigger than say 300px in width.
Both ways are ok, depends greatly on exactly what you need to achieve in terms of performance:
To me seems that, the simplest way for you would be on client side, then you only need a few lines of JavaScript to do it:
var img = new Image();
img.onload = function() {
console.log(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
On server side is also possible but you will need to install GraphicsMagick or ImageMagick. I'd go with GraphicsMagick as it is faster.
Once you have installed both the program and it's module (npm install gm) you would do something like this to get the width and height.
gm = require('gm');
// obtain the size of an image
gm('test.jpg')
.size(function (err, size) {
if (!err) {
console.log(size.width + 'x' + size.height);
}
});
Also, this other module looks good, I haven't used it but it looks promsing https://github.com/netroy/image-size
To get the img urls from the html string
You can load your html string using a simple http request, then you need to use a regexp capture group to extract the urls, and if you're wanting to match globally g, i.e. more than once, when using capture groups, you need to use exec in a loop (match ignores capture groups when matching globally).
This way you'll have all the sources in an array.
For example:
var m;
var urls = [];
var rex = /<img[^>]+src="?([^"\s]+)"?\s*\/>/g;
// this is you html string
var str = '<img src="http://example.com/one.jpg />\n <img src="http://example.com/two.jpg />';
while ( m = rex.exec( str ) ) {
urls.push( m[1] );
}
console.log( urls );
// [ "http://example.com/one.jpg", "http://example.com/two.jpg" ]
Hope it helps.

Creating a Parse.File with Javascript SDK

I've followed the letter of the law (Javscript SDK) along with numerous variations but thus far I have not been able to save an image to a Parse.File. I'm starting think this is code they never finished before they abandoned the platform?
This is my error:
Failed to construct 'File': 2 arguments required, but only 0 present.
This is my code:
var base64 = $base64.encode(unescape(encodeURIComponent('a string')));
var file = new Parse.File("logo.png", { base64: base64});
file.save().then(function(){
var newLogo = new Parse.File();
newLogo.set('step2.png', file);
newLogo.save().then(function(){
offer.set("Alogo.png", newLogo);
offer.save();
}).then(function(){}, function(error){console.log(error);});
});
It saves no image or note of 'Alogo.png' or anything dealing with a logo in my ParseDB. Any help you could offer would be much appreciated!
For once, Parse was right on point. The issue was not with my code but with Angular and it's lack of recognition of 'file' tags in html. This post/tutorial proved very useful as it has a directive that enables angular to recognize post tags so that angular can add files to the model.
http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

Reading image capture files in PhoneGap

I'm working on a PhoneGap application that captures images using the camera and, later, uploads them. There are two modes of operation for camera in PhoneGap: raw base64 encoded data or a file URI.
The docs themselves say:
Note: The image quality of pictures taken using the camera on newer
devices is quite good. Encoding such images using Base64 has caused
memory issues on some of these devices (iPhone 4, BlackBerry Torch
9800). Therefore, using FILE_URI as the 'Camera.destinationType' is
highly recommended.
So I'm keen to use FILE_URI option. This works great and you can even show the images in IMG tags. The URL looks like this:
file://localhost/var/mobile/Applications/4FE4642B-944C-449BB-9BD6-1E442E47C7CE/tmp/photo_047.jpg
However, at some point later I want to read the contents of the file to upload to a server. I was going to do this using the FileReader type. This doesn't work and I think it's because I can't access the file at the URL above.
The error code I get back from readDataUrl is 1 > FileError.NOT_FOUND_ERR = 1;
Any ideas how I can get to the file? I tried just accessing the last part of the path (photo_047.jpg) based on another sample I saw but no luck.
I'm just getting started with PhoneGap, and given the age of this question you may have found an answer already, but I'll give it a try anyway.
First, would you be able to use the built-in FileTransfer object? It takes a file: URI as an argument.
If FileTransfer won't work for you, and you need to read the file data yourself, you'll need the PhoneGap File objects, like FileReader , as you said. But most of those expect a plain pathname -- not a URI -- to specify the file to work with. The reason you're getting NOT_FOUND_ERR is because it's trying to open a file named file:/localhost/var....
Here's a quick one-liner to extract the path part from your URI:
var path = /file:\/\/.*?(\/.*)/.exec(fileuri)[1];
Hope this helps!
The answer from jgarbers was of help to me but it did not solve the problem. I realized the camera stores photos in Temp folder instead of Document folder. Setting my local file system to temporary allowed it to find the correct location for the camera images.
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, ...
...
var path = /file://.?(/.)/.exec(fileuri)[1];
Ref. above jgarbers and Rik answers (solution has been tested successfully on iOs 7)
you can user the file transfer plugin for uploading any file to the server.
//// pass your file uri to the mediafie param
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your service method url
var objUrl = http://example.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}

Categories