How to save an image to a specific folder with Cloudinary? - image-uploading

I want to save an image file in a specific folder on Cloudinary. The folder name is "userimg".
Here is my code to save without a folder.
My cloudinary and folder directory.

Cloudinary Upload API supports a folder parameter. See - https://cloudinary.com/documentation/image_upload_api_reference#upload
Please try adding:
formData.append('folder', 'userimg');
You can also include the folder in the public ID, e.g., 'myfolder/myimageid'.
Also, see:
https://support.cloudinary.com/hc/en-us/articles/202520902-Can-I-create-folders-in-my-Cloudinary-account-

the code of save an image file in specific folder on cloudinary:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div class="container">
<div class="card">
<img src="http://fillmurray.com/g/300/300" id="img-preview" />
<label class="file-upload-container" for="file-upload">
<input id="file-upload" type="file">
Select an Image
</label>
</div>
</div>
<script>
var cloudeinary_url = "your_cloudeinary_url";
var upload_presets = "your_upload_presets";
var ingpriview = document.getElementById("img-preview");
var fileupload = document.getElementById("file-upload");
fileupload.addEventListener('change',
function (event) {
var files = event.target.files[0];
var formData = new FormData();
formData.append('file', files);
formData.append('upload_preset', upload_presets);
formData.append('folder', 'itemimg'); // itemimg is folder name
axios({
url: cloudeinary_url,
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: formData
}).then(function (res) {
document.getElementById("img-preview").src = res.data.secure_url;
console.log(res);
}).catch(function (err) {
console.log(err);
});
});
</script>

Related

Use Rest API to return link from sharepoint list

I'm trying to use REST API in SharePoint to getlistitems to display the link from a hyperlink field from my sharepoint list.
I AM successfully using the code to display the title field - but NOT the url from the hyperlink field.
I've tried appending the url in the code below with "/_api/web/lists/getbytitle('test')/items**?$select=URL**"
without success.
<html>
<body>
<div>
<input type="button" id="btnSubmit" value="Get List Data using Rest API">
</div>
<div id="divResults" unselectable="on"></div>
<script src="/jquery.com/jquery-3.5.1.min.js" unselectable="on"></script>
<script unselectable="on">
$(function () {
$("#btnSubmit").on("click", function () {
getListData();
});
});
function getListData() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('test')/items";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: onQuerySucceeded,
error: onQueryFailed
});
}
function onQuerySucceeded(data) {
var listItemInfo = '';
$.each(data.d.results, function (key, value) {
listItemInfo += '<b>Title:</b> ' + value.Title + '<br />';
});
$("#divResults").html(listItemInfo);
}
function onQueryFailed() {
alert('Error!');
}
</script>
</body>
</html>
In onQuerySucceeded function, Try this line:
listItemInfo += '<b>UrlFromHyperLinkField:</b> ' + value.TestHyperLink.Url+ '<br />';
In my side, the HyperLink named "TestHyperLink", you can replace this field name with yours to make it work.

Image is not rendering from dynamic image path while using express html-pdf package

I'm using the Html-pdf package to generate and download pdf in an express-MongoDB application. Here is the route, where I've used the Html-pdf package.
//#route - GET /generate PDF
router.get("/generateReport/:id", async (req, res) => {
const tableDataById = await newsModel.findById(req.params.id);
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById}, (err, data) => {
if (err) {
res.send(err);
} else {
var assesPath = path.join('file://',__dirname,'../public/');
assesPath = assesPath.replace(new RegExp(/\\/g), '/');
var options = {
"height": "11.25in",
"width": "8.5in",
"header": {
"height": "20mm",
},
"footer": {
"height": "20mm",
},
"base": "file:///" + assesPath
};
pdf.create(data, options).toBuffer(function (err, buffer) {
if (err) {
res.send(err);
} else {
res.type('pdf');
res.end(buffer,'binary')
}
});
}
});
});
I've used ejs template engine. Here is the code of the "pdf.ejs" file which I rendered in the before mentioned route.
<div class="container">
<div class="row">
<div class="col-md-4">
<img class="card-img-top" src="<%= output.newspapers[0].logo %>">
<h1><%= output.newspapers[0].newsPaperName %></h1>
</div>
<div class="text-center">
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
</div>
</div>
</div>
Here is the screenshot of my application, which failed to render the dynamic image path
Here, I've also included a screenshot of the sample JSON data, in which the path of the images is included
Image src needs absolute path for rendering dynamic image path from the ejs file that you want to generate as a pdf file.
inside your controller, instead of doing this:
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById}
Do this: send a variable that contains the absolute path
ejs.renderFile(path.join(__dirname, '../views/pages/', "pdf.ejs"), {output:tableDataById,dirname: __dirname}
and inside the ejs file instead of doing this :
<img class="img-fluid" id="test" src="<%= output.image %>" alt="">
Do this : add the variable dirname and go one step back to get the public path where you are saving your image
<img class="img-fluid" id="test" src="<%= dirname %>/../public/<%= output.image %>" alt="">
Hope this will help solving your problem. Happy coding !!

Looking to access mongoose array of strings

I am able to access all elements from my schema except for the array thats where it gets tricky for me. when I upload a pic and i use the developers console to see what link the image has it says " /lock.png " something like that and it does not show the picture just load the pic properly. So basically I need help saving the array elements and then loading them for the images:[String]
thanks
app.js
var postSchema = new mongoose.Schema({
title:String,
price:Number,
name: String,
image: String,
images: [String],
desc: String
})
app.post("/posts", function(req, res) {
//get data from and add to posts array
var title = req.body.title;
var price = req.body.price;
var image = req.body.image;
var desc = req.body.desc;
var images = req.body.images;
var newPost = { title: title, price: price, images: images, image: image, desc: desc};
//create new post and save to database
postModel.create(newPost, function(err, newlyCreated) {
if(err){
console.log("error with new post");
}else{
res.redirect("/posts");
}
});
//posts.unshift(newPost);
inside my ejs file
<input name="images" class="uploadFile btn btn-primary btn-block" type="file" multiple id="gallery-photo-add" placeholder="Choose File" >
<% posts.forEach(function(post) { %>
<div class = "row">
<div class ="col-xs-8">
<p><%= post.title %></p>
</div>
<div class ="col-xs-4">
<p>$<%= post.price %></p>
</div>
</div>
<% if(post.image === ""){ %>
<% }else { %>
<img class="img-rounded img-responsive half img-thumbnail" src="<%= post.image %>">
<% } %>
<img class="img-rounded img-responsive half img-thumbnail" src="<%= post.images %>">
<p><%= post.desc%></p>
<p>
More Info
</p>
<% }); %>
<script type="text/javascript">
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="img-rounded img-responsive img-thumbnail">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
posts.images[i].set(i, input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
</script>
I just get this image
this is what comes up in my database
{ "_id" : ObjectId("57550dfd1fdfa6f701be755f"), "title" : "", "price" : 5555, "desc" : "", "images" : [ "city-1026227_960_720.jpg" ], "__v" : 0 }
I just made a simple working example that outputs an image in an array that was saved to the database. I don't see what you are doing doing for res.render. I mean in my example the string was saved to the database and it displays an img from a remote server at http://placehold.it/350x150
var express = require("express"),
app = express(),
mongoose = require("mongoose"),
ejs = require("ejs");
mongoose.connect("mongodb://localhost/arrays");
app.set("view engine" , "ejs")
var postSchema = mongoose.Schema({
title : String,
images : [String]
})
var Post = mongoose.model("posts", postSchema);
Post.remove({},function(err, data){
console.log("removed")
})
Post.create({title : "test", images : ["http://placehold.it/350x150", "two"]}, function(err, data){
if(err) throw err;
console.log(data);
})
app.get("/", function(req, res){
Post.findOne({"title" : "test"}, function(err, data){
if(err) throw err;
res.render("array", {data: data})
})
})
app.listen(3000, function(){
console.log("listening on 3000")
})
array.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>arrays</title>
</head>
<body>
<img src="<%= data.images %>" alt="">
</body>
</html>
EDIT: you could also try something like src="localhost:port/<%= post.images[0] %> and I'm wondering if your src="<%= post.image %>" works because if it doesn't your problem could be the way your loading the files and not the way you are using arrays.

cannot submit a form with jQuery

I've this form
<form id="frm_main" action="#" method=POST>
<input type=hidden name="MAX_FILE_SIZE" value="100000" />
<input id='file' name="file" type="file">
<input type=submit id='btn_import' name='btn_import' value='Importar' />
<input type=hidden id="uploadResponseType" name="mimetype" value="html" />
<input type=hidden id="func" name="func" value="upload" />
<div id="uploadOutput"></div>
</form>
So, the problem became when I try to post the upleaded file. If I use ajaxSubmit function the form is submited but it doesn't return to the page; and if I use $.ajax function, it doesn't sent the uploeade file. The thing is that I need to return to the same page because I've to do some stuff with the file content. I've already tried lot of combinations but I'm still having the same results. The code to handle submit look like this
$( '#frm_main' ).bind( 'submit', function( e ) {
// e.preventDefault(); // <-- important
$( this ).ajaxSubmit({
target: '#uploadOutput', // <-- div container
type: "POST", // <-- override, just in case.
url: "/process.php", // <-- server-side handler
data: "func=upload", // <-- parameter for post purpouse
beforeSubmit: function(a,f,o) {
o.dataType = $('#uploadResponseType').val(); // should be 'html'.
$('#uploadOutput').html('Submitting...');
},
success: function(data) {
var $out = $('#uploadOutput');
$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
$out.append('<div><pre>'+ data +'</pre></div>');
}
});
return false;
});
And I've already tried with next code
$('#frm_main').bind('submit', function() {
var formdata = $(this).serialize();
$.ajax({
url: '/process.php',
data: formdata,
dataType: 'html',
success: function(data){
var $out = $('#uploadOutput');
$out.html('Form success handler received: <strong>' + typeof data + '</strong>');
}
});
return false;
});
And process.php code looks like this
switch($_POST['func']) {
case 'upload' :
$output = upload_file ();
echo $output;
break;
default :
echo "<BR/>INVALID";
break;
}
?>
Can somebody help me with this situation, please? Any help will be gratefully appreciated
Don't you need form enctype="multipart/form-data" to upload files?

dialog does not come up after uploading asp.net mvc 2

my dialog does not popup after successfull upload? the upload works fine but $("#dialog-confirm").dialog does not work?
<h2>
upload Data</h2>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="../../Scripts/jqueryform.js" type="text/javascript"></script>
<script src="../../Scripts/jblock.js" type="text/javascript"></script>
<script src="../../Content/jquery-ui-1.8.12.custom/js/jquery-ui-1.8.12.custom.min.js"
type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.8.12.custom/css/ui-lightness/jquery-ui-1.8.12.custom.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$("#ajaxUploadForm").block({ message: '<h1><img src="/Content/busy.gif" /> uploading file...</h1>' });
},
success: function (result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
//alert(result.message);
//does not popup??
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Ok":
function () {
alert('ok');
$(this).dialog("close");
}
,
Cancel: function () {
$(this).dialog("close");
}
}
});
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Home")%>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file</legend>
<label>
File to upload:
<input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
</form>
public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file)
{
// TODO: Add your business logic here and/or save the file
System.Threading.Thread.Sleep(2000); // Simulate a long running upload
// Return JSON
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I see that you are using the jquery.form plugin for AJAXifying the form and returning JSON from your controller action. Here's what the documentation says about this scenario:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads.
So for this to work the response from the server needs to look like this:
<textarea>{ message: 'file uploaded successfully' }</textarea>
Is it what this custom FileUploadJsonResult is doing in your controller action?