I have a responsive-image-gallery- code in HTML5 that fetches an image from Filker. I want to fetch image from img folder and get the title automatically from the .jpg name this is the code
// fetch images from Flickr
function fetch_images() {
$.getJSON(api_flickr, {
tags: $("#searchinput").val(),
tagmode: "any",
format: "json"
})
.done(function(data) {
$.each(data.items, function(i, item) {
var url = item.media.m;
var title = item.title;
var elem = $("<div class='my show'><img src='"+url+"'/><div>"+
title+"</div>");
images.append(elem);
});
// add more-div and resize
images.append($("#morediv").clone().removeAttr("id"));
resize_images();
});
}
Flicker has an API that provides JavaScript with a JSON-formatted list of filenames.
In order for your script to do the same, you need to either provide it with the same type of API (maybe with a PHP script) or with a list of the filenames in the img folder.
References:
JSON - Learn what JSON is
PHP Script - Learn how to create a PHP script to output what you need
Related
I am trying to upload image to an Etsy listing via their API v2. Their documentation have code example of image upload in PHP, in which the POST request body parameter is given like this
$params = array('#image' => '#'.$source_file.';type='.$mimetype);
How would I go about replicating this in JavaScript? I have tried sending the image blob as the image parameter but it does not seem to be working.
Edit: I am using npm oauth package. Here is my complete code that I am using to call the API.
var oauth1 = new OAuth1.OAuth(
'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r%20listings_w%20listings_d',
'https://openapi.etsy.com/v2/oauth/access_token',
'api_key',
'api_secret',
'1.0A',
null,
'HMAC-SHA1'
);
oauth1.post(
'https://openapi.etsy.com/v2/listings/915677000/images',
req.user.etsy.oauth_token,
req.user.etsy.oauth_token_secret,
{
'listing_id': 915677000,
'image': <image has to go here>
},
'multipart/form-data',
function (e, data, response){
if (e) console.error(e);
// let body = JSON.parse(data);
console.log(data);
res.redirect('/create-listings')
});
In Cloudinary Django SDK documentation for direct from browser uploading it gives example below for direct_upload_complete view.
#csrf_exempt
def direct_upload_complete(request):
form = PhotoDirectForm(request.POST)
if form.is_valid():
form.save()
ret = dict(photo_id = form.instance.id)
else:
ret = dict(errors = form.errors)
return HttpResponse(json.dumps(ret), content_type='application/json')
Immediately after this example it says Having stored the image ID, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image: and gives template code example as follows:
{% load cloudinary %}
{% cloudinary photo.image format="jpg" width=120 height=80 crop="fill" %}
I am confused by this template code example because it does not relate at all to the Django view code which has response name ret. Screenshot of documentation is below.
What would I need to do to use Javascript to create a variable from the JSON object named ret and display it on the template page?
Below is Javascript I am using on the example's upload_prompt.html template. It works fine, returning a thumb of uploaded image and some Cloudinary data that show after image is uploaded (on cloudinarydone event).
But I also want to get the uploaded photo's Model id to create a link to the photo using the id.
Where in below Javascript can I get the photo_id key value from the JSON object named ret?
<script>
$(function () {
$('#direct_upload input[type="file"]')
.cloudinary_fileupload({
dropZone: '#direct_upload',
start: function (e) {
$('.status').text('Starting upload...');
},
progress: function (e, data) {
// $('.status').text('Uploading...');
$(".status").text("Uploading... " + Math.round((data.loaded * 100.0) / data.total) + "%");
},
fail: function (e, data) {
$(".status").text("Upload failed");
}
})
.on('cloudinarydone', function (e, data) {
$('.status').text('Updating backend...');
$.post(this.form.action, $(this.form).serialize()).always(function (result, status, jqxhr) {
$('.status').text(result.errors ? JSON.stringify(result.errors) : status);
});
var info = $('<div class="uploaded_info"/>');
$(info).append($('<div class="image"/>').append(
$.cloudinary.image(data.result.public_id, {
format: data.result.format,
width: 150,
height: 150,
crop: "fill"
})
);
$(info).append($('<div/>').append('image/upload/' + data.result.path));
$('.uploaded_info_holder').append(info);
});
});
</script>
Thanks to Brian Luk at Cloudinary Support, getting photo_id value is done in template's javascript POST request callback.
Maybe there are betters ways to do this, but I simply created variable photoid and then used that variable to create Photo model url.
$.post(this.form.action, $(this.form)
.serialize()).always(function (result, status, jqxhr) {
$('.status').text(result.errors ? JSON.stringify(result.errors) : status);
var photoid = JSON.stringify(result.photo_id);
$(info).append($('<div/>').append('link'));
Currently I am using the following approach where it is giving details of file but not the actual object it seems like one we get from in javascript/jQuery. Does any one having the clue how to get the file object from File URI /native URI from mobile ios/android filesystem using cordova and javascript?
Below is the snippet I am using currently..
window.resolveLocalFileSystemURL(
filepath,
function(fileEntry) {
fileEntry.file(
function(file) {
var reader = new FileReader();
reader.onloadend = function() {
var imgBlob = new Blob([this.result], {type: "image/jpeg"});
var uploadedFile = imgBlob;
uploadedFile.name = file.name;
alert("Importing Asset from Camera.. " + uploadedFile.name);
alert(uploadedFile.type);
alert(uploadedFile.size);
importAsset(uploadedFile);
};
reader.readAsArrayBuffer(file);
},
function(error) { alert("Error in fileEntry.file():" + error) })
},
function(error) { alert("Error in window.resolveLocalFileSystemURL():" + error) }
);
Note: FileTransfer.upload() will not work in my case.
Above snippet I am using after taking from Append image file to form data - Cordova/Angular after going through the existing Q&A from #SO
Base64 Image Upload will work both in iOS/Android as I have tried:
As for iOS There is only one way to show image is using base64 format.You can use cordova-camera-plugin to to generate base64 image and put on img tag of HTML.I have set the flag to get data in jpeg,base64 in camera plugin.
<img id="cardImg">
Store the base64 image in javascript variable as:
var imgdata=data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
Then Simply pass data to img tag of HTML as:
cardImg.src=imgdata;
Done!
I am writing a asp.net web api web service. Along with the service I am also writing a tester so the web service can be tested.
the tester allows you to post and receive either JSON or XML. I am processing the response using jquery ajax. I am fine using JSON and the below works fine.
the JSON response
{"ItemLabel":
{"Requisition":"W44DQ18255TS42 ",
"Nsn":"5999-01-100-5901",
"FscNiin":"5999011005901 ",
"Cage":"1CAY9",
"PartNumber":"",
"Nomen":"CONTACT,ELECTRICAL ",
"Quantity":"1",
"Ui":"EA",
"UiDesc":"",
"PurchOrderNbr":"SPM907-85-5-4444",
"RlseNbr":"TS0042",
"Clin":"0042 ",
"Lot":"",
"Preservation":"",
"DatePreserved":"",
"ShelfType":"",
"Shelf1":"",
"Exp1":"",
"CureDt1":"",
"CureInsp1":"",
"Shelf2":"",
"Exp2":"",
"CureDt2":"",
"CureInsp2":"",
"Serials":"",
"Serial":null,
"SerialInters":null,
"UnitPerInt":"1",
"TypeLbl":"ITEMx1"
},
"filePaths":["https://xxxxxxxxxxx.dir.ad.dla.mil/pdf/email_ITEMLBL__W44DQ18255TS42 _682895.pdf"]
}
and I can process the results using jquery ajax as follows.
success: function (result) {
$('#Spinner129').hide();
self.jsonResponse129(JSON.stringify(result));
self.hasSuccess129(true);
self.successMessage129("Success! Please view the response in the JSON Response tab below.");
$.each(result.filePaths, function (i, path) {
window.open(path, '_blank');
});
},
although I am struggling a bit to do the same thing with the xml response how do I get the values in filepaths?
here is the xml response
<FobOriginWebService129PLabelOutput xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/VSM">
<ItemLabel>
<Cage>1CAY9</Cage>
<Clin>0042 </Clin>
<CureDt1></CureDt1>
<CureDt2></CureDt2>
<CureInsp1></CureInsp1>
<CureInsp2></CureInsp2>
<DatePreserved></DatePreserved>
<Exp1></Exp1>
<Exp2></Exp2>
<FscNiin>5999011005901 </FscNiin>
<Lot></Lot>
<Nomen>CONTACT,ELECTRICAL </Nomen>
<Nsn>5999-01-100-5901</Nsn>
<PartNumber i:nil="true" />
<Preservation></Preservation>
<PurchOrderNbr>SPM907-85-5-4444</PurchOrderNbr>
<Quantity>1</Quantity>
<Requisition>W44DQ18255TS42 </Requisition>
<RlseNbr>TS0042</RlseNbr>
<Serial i:nil="true" />
<SerialInters i:nil="true" />
<Serials></Serials>
<Shelf1></Shelf1>
<Shelf2></Shelf2>
<ShelfType>SHL0</ShelfType>
<TypeLbl>ITEMx1</TypeLbl>
<Ui>EA</Ui>
<UiDesc></UiDesc>
<UnitPerInt>1</UnitPerInt>
</ItemLabel>
<filePaths xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>https://xxxxxxxxxxx.dir.ad.dla.mil/pdf/email_ITEMLBL__W44DQ18255TS42 _405955.pdf</d2p1:string>
</filePaths>
</FobOriginWebService129PLabelOutput>
not sure how to process it in the jquery ajax success section here was my attempt.
success: function (result) {
$('#Spinner129').hide();
self.hasSuccess129(true);
self.successMessage129("Success! Please view the response in the XML Response tab below.");
self.xmlResponse129(JSON.stringify(result));
// xmlDoc = $.parseXML(result),
// $xml = $(xmlDoc),
// $filePath = $xml.find("filePaths");
// now what?
},
The file path is nested within the children of filePaths node.
<filePaths xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>https://xxxxxxxxxxx.dir.ad.dla.mil/pdf/email_ITEMLBL__W44DQ18255TS42 _405955.pdf</d2p1:string>
</filePaths>
Once you have $filePaths as following:
$filePaths = $xml.find("filePaths");
You can access its children and then get its text:
$filePaths.children().each(function () {
//console.log($(this).text()); // print to test
// https://xxxxxxxxxxx.dir.ad.dla.mil/pdf/email_ITEMLBL__W44DQ18255TS42 _405955.pdf
// open in new window
window.open($(this).text(), '_blank');
});
Everything looks fine. To get filePath value try this:
$filePath.text();
Simple question. I have a .doc file generated in my mojolicious app. I want to download it. That's my question, how do I get the browser to download it?
I'm using the CPAN module MsOffice::Word::HTML::Writer to generate the doc.
Here is the sub routine in my mojolicious app, it is called by an Ajax request in Jquery:
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
$self->res->headers->content_disposition("attachment;filename=file.doc");
$self->res->headers->content_type('application/msword');
$self->render(data => $doc->content);
}
Here is my Ajax request in Jquery:
var request = $.ajax({
url: "/down_doc",
type: "post",
data: {'data': data},
});
request.done(function(response, textStatus, jqXHR) {
window.location.href = response;
});
I know that my Ajax "done" handler is wrong, I was just experimenting. How do I make my webpage prompt to save and download the .doc file?
You where pretty close, but I would recommend either of the following options...
File Download Processing with Mojolicious
You can install the plugin Mojolicious::Plugin::RenderFile to make this easy.
Example
plugin 'RenderFile';
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
$self->render_file('filepath' => "/docs/file.doc");
}
Or if you want to only use Mojo the following will work, and is explained further at the link below.
use Cwd;
app->static->paths->[0] = getcwd;
sub down_doc {
my $self = shift;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "My new Doc",
WordDocument => {View => 'Print'},
);
$doc->write("Content and Stuff");
my $save = $doc->save_as("/docs/file.doc");
shift->render_static("/docs/file.doc");
}
Reference
This really isn't a problem on the server side, but rather that you can't save the response from an ajax request without using the (relatively new) File API. I would suggest replacing the ajax with a temporary form:
$('<form method="post" action="/down_doc">')
.append(
$('<input type="hidden" name="data">')
.attr("value", JSON.stringify(data))
)
.appendTo('body')
.submit();
When form is submitted and your /down_doc handler replies with the appropriate content-disposition header and the document data, the browser will do the work of handling the file save.
If you're not planning to use the file on the server after the request, this line can be removed:
my $save = $doc->save_as("/docs/file.doc");