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')
});
Related
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'));
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");
I am using Froala editor for my website. This editor have built in image upload function - image upload is working fine, but I am having trouble with response.
This is from the documentation:
The server processes the HTTP request.
The server has to process the upload request, save the image and return a hashmap containing a link to the uploaded image. The returned hashmap needs to look like: { link: 'path_to_uploaded_file/file.png' }
This is my function for returning link:
public function froala_upload()
{
header('Content-type: application/json');
$folder = 'public/img/media';
$slika = $this->site->single_upload($folder, 'jpg|jpeg|png|bmp|JPG|JPEG|PNG|BMP');
$link = array("link" => $slika);
echo json_encode($link);
}
This is JS code:
$('textarea').editable({
inlineMode: false,
imageUploadParam: "userfile",
imageUploadURL: "<?php echo base_url() ?>admin/froala_upload",
// Set the image error callback.
imageErrorCallback: function (data) {
// Bad link.
if (data.errorCode == 1) {
console.log(data);
}
// No link in upload response.
else if (data.errorCode == 2) {
console.log(data);
}
// Error during file upload.
else if (data.errorCode == 3) {
console.log(data);
}
}
});
When I upload image I get following error:
Object { errorCode=1, errorStatus="Bad link."}
And this is response that I get:
{"link":"7d59d61.jpg"}
What seem to be a problem?
Froala image upload documentation
You must return the absolute image path :
$link = array("link" => '/img/media/'.$slika);
Because Froala looks for it to http://example.com/7d59d61.jpg
The problem is that the image cannot be loaded from the returned link. You'd have to make sure that the image can be accessed from it. Froala Editor uses the link you return for src attribute from img tag. I think you'd have to do something like:
$link = array("link" => $slika . 'public/img/media');
I am working on a file uploader for my app and I settled on Filepicker.io. Everything is working fine except for one thing..When I upload an image to S3 I can only upload the URL that Filepicker returns (not the image itself).
The below is successful, but
Template.new_aphorism.events({
'change #attachment': function(event){
var savedFile = JSON.stringify(event.fpfile);
var parsedJSON = eval('('+savedFile+')');
var url=parsedJSON.url;
$('input[name=new_aphorism_image]').val(url);
console.log("saved file is:" + savedFile);
console.log(url);
filepicker.store(url, {location: 'S3'}, function(fpfile){
output.html('Uploaded: '+fpfile.filename+'');
}, function(fperror){
output.text(fperror.toString());
}, function(progress){
output.text("Uploading... ("+progress+"%)");
});
}
});
I get back as my message:
File stored in S3 at VnAa2YsOS6wOECNMWpwn_temp.txt and available at https://www.filepicker.io/api/file/vVtWTOl7QqOJ7gPmXkHQ
I have tried passing this and event.fpfile into my filepicker.store function but it just doesn't work.
Solved.
In the same function:
var file = event.fpfile;
filepicker.store(file, {location: 'S3'}, function(fpfile){