Form serialize data:image/png;base64 data type json - resize

Hello i have been developing cms but now got revision add one feature crop and resize images before upload in codeignter, here is simple demo
$('#btnsubmit').on("click", function(e) {
e.preventDefault();
$.ajax({
url: base_url + "welcome/add",
type: "POST",
data: $('#form').serialize(), //extract value in form
dataType: "JSON",
success: function(data) {
if (data.status) //if success close modal and reload ajax table
{
alert('success');
} else {
alert('failed');
}
$('#btnsubmit').text('save'); //change button text
$('#btnsubmit').attr('disabled', false); //set button enable
}
});
and this is my controller
$dataURL=$this->input->post('images_crop');
//$dataURL = $_POST["imageData"];
$dataURL = str_replace('data:image/png;base64,', '', $dataURL);
$dataURL = str_replace(' ', '+', $dataURL);
$image = base64_decode($dataURL);
$filename = date("d-m-Y-h-i-s") . '.' . 'png'; //renama file name based on time
$path = set_realpath('uploads/product/');
file_put_contents($path. $filename, $image);
$data = array (
'id_product_post'=>$this->input->post('id_product_post'),
'foto'=>$filename
);
$this->db->insert('li_product_foto',$data);
all i have got images success store in database and folder but the images is blank and 0kb, where do i wrong, thanks
/---------Solved by my self----------/
The reason why file is 0kb and blank cause i forget to remove old doc which came from Here Please see the code controller i make command, Hope some one in the future get help from this

Related

Append code to overwrite a PDF if a file of the same name already exists in the Google Drive folder

I have this script to save my spreadsheet in the Google Drive Squads folder..
The name of the saved file is according to the value that is in cell H2 of the Gerais page, sometimes the name repeats and when saving, a new file is created instead of subscribing to the existing one, I would like to add in this code the option that if a file with the same name as this new one already exists, instead of having two files with the same name in the Google Drive Squads folder, the old one will disappear completely and only make the new file available
//Create PDF
SpreadsheetApp.flush();
var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/' + // Best to place the line break after '+'
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + // SHEET ID
'/export?format=pdf' +
'&size=0' +
'&portrait=true' +
'&fitw=true' +
'&top_margin=0' +
'&bottom_margin=0' +
'&left_margin=0' +
'&right_margin=0' +
'&sheetnames=false&printtitle=false' +
'&pagenum=false' +
'&gridlines=false' +
'&fzr=FALSE' +
'&gid=' +
'XXXXXXXXXXXX'; //SHEET PAGE ID
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdfBlob = docurl.getBlob();
// Get filename from sheet "Gerais", cell "H2"
var fileName = spreadsheet.getSheetByName("Gerais").getRange("H2").getValue();
// Create file from blob and name it
// The newFile is placed in the root folder by default
var newFile = DriveApp.createFile(pdfBlob).setName(fileName);
// if folder exists use next
if (DriveApp.getFoldersByName("Squads").hasNext()){
var folder = DriveApp.getFoldersByName("Squads").next();
// if folder does not exist
} else {
var folder = DriveApp.createFolder("Squads");// new folder created in the root folder by default
}
folder.addFile(newFile); // add new file to folder
DriveApp.removeFile(newFile); // remove file from root folder
I tried to create an interaction between IF and ELSE too to make the file name match the same as I did for the folder name but I was unsuccessful in trying
Problem
Overwriting existing File in a Folder by its name (presumably unique).
Solution
How about checking if a file with the name written into fileName variable exists and if so, removing it before adding the newly created one? Modification will look something like this (your script has be authorized with one the scopes required for the API):
//prepare new file and Squads folder;
var existing = folder.getFilesByName(fileName); //returns file iterator;
var hasFile = existing.hasNext(); //check if iterator isn't empty;
if(hasFile) {
var duplicate = existing.next(); //access file;
//delete file;
var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,{
method: 'delete',
muteHttpExceptions: true,
headers: {'Authorization': 'Bearer '+token}
});
if(dres.getResponseCode()>=400) {
//handle errors;
}
}
//continue: add file, remove from root, etc;
Notes
The way you define query parameters is the common case of a pyramid of doom. Besides, each parameter is hardcoded, which makes the export inflexible. To avoid this, use objects to configure them (as query is nothing more than a set of key-value pairs):
var params = {
format: 'pdf',
size: 0,
portrait: true,
fitw: true,
top_margin: 0,
bottom_margin: 0,
left_margin: 0,
right_margin: 0,
sheetnames: false,
printtitle: false,
pagenum: false,
gridlines: false,
fzr: 'FALSE',
gid: 'XXXXXXXXXXXX'
};
//append params to the url;
var theurl = 'base?'+Object.keys(params).map(function(key){
return key+'='+params[key];
}).join('&');
Updates
Corrected UrlFetchApp.fetch() call as method should be a parameters object property and not an argument.
Reference
Drive API delete reference;

how to update file name dynametically when upload in ionic 4

hi i am using Ionic 4 with angular 7 in my project.
Currently i am facing difficulties on upload image.
File Transfer works fine with a static name like:
let options: FileUploadOptions = {
fileKey: 'file',
fileName: 'name.jpg',
headers: {}
.....
}
it working fine. but i need dynamic name. so i updated accordingly
this.temp_image_name = new Date().getTime()+'.jpg';
let options: FileUploadOptions = {
fileKey: 'file',
fileName: this.temp_image_name,
headers: {}
.....
}
but it not working and file name return empty. have any idea on this issue.
Thanks
i solved the issue in server side, before save or upload i renamed the file.
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = time() . '.' . end($temp);
$target_path = $target_path . $newfilename;
and return the newfileName to use the name for next use.
I tested the snippet just to be sure that combining a number getTime() and a string was ok, but it didn't seem to have any issues:
You are using a class level variable which may be being affected by something.
Try:
let temp_image_name = new Date().getTime()+'.jpg';
let options: FileUploadOptions = {
fileKey: 'file',
fileName: temp_image_name,
headers: {}
.....
}
It seems like you should not be using this plugin at all anyway as it is deprecated.

Rails 5 jquery file upload image orientation rotated 90 degrees for portraits

I'm having trouble with the image orientation after uploading an image to my s3 account. Portrait images are rotated 90 degrees when images are displayed. Here is the coffee script I am using from the Heroku - Direct to S3 Image Uploads in Rails tutorial.
# Use this instead of jQuery -> with Turbo links. Turbo links will trigger the ready page:load.
document.addEventListener 'turbolinks:load', ->
$('.directUpload').find('input:file').each (i, elem) ->
fileInput = $(elem)
form = $(fileInput.parents('form:first'))
submitButton = form.find('input[type="submit"]')
progressBar = $('<div class=\'bar\'></div>')
barContainer = $('<div class=\'progress\'></div>').append(progressBar)
fileInput.after barContainer
fileInput.fileupload
fileInput: fileInput
url: form.data('url')
type: 'POST'
autoUpload: true
formData: form.data('form-data')
paramName: 'file'
dataType: 'XML'
replaceFileInput: false
progressall: (e, data) ->
progress = parseInt(data.loaded / data.total * 100, 10)
progressBar.css 'width', progress + '%'
return
start: (e) ->
submitButton.prop 'disabled', true
progressBar.css('background', 'green').css('display', 'block').css('width', '0%').text 'Loading...'
return
done: (e, data) ->
submitButton.prop 'disabled', false
progressBar.text 'Uploading done'
# extract key and generate URL from response
key = $(data.jqXHR.responseXML).find('Key').text()
url = '//' + form.data('host') + '/' + key
# create hidden field
input = $('<input />',
type: 'hidden'
name: fileInput.attr('name')
value: url)
form.append input
return
fail: (e, data) ->
submitButton.prop 'disabled', false
progressBar.css('background', 'red').text 'Failed'
return
return
return
I'm using an image_tag to display the image from my S3 account.
= image_tag current_company.logo.image_url
I'm not sure what I need to do to fix the orientation. I did find this in the blueimp/jQuery-File-Upload/wiki/Options#imageorientation, but have no clue if this is what I am looking for or how to use it if it is. Any help would be appreciated.
This is my first time posting on here so please be gentle.

Trying to use angular-recorder: how to send result file to server?

I'm using this https://github.com/logbon72/angular-recorder and eventually i'll get mp3 file. How i can sent this file to server by POST request ?
Can i send the mp3 file to server or Blob only ?
i can not get result voice file.
logbon72/angular-recorder is a Fork of sathyapulse/angular-recorder. There, some people comment similar issues. Then copy the reply I sent to one of them:
Just search "control.save" in angular-audio-recorder.js file ( near line 377 ) and write this:
control.save = function (fileName) {
if (!service.isAvailable() || status.isRecording || !control.audioModel) {
return false;
}
var formData = new FormData();
var request = new XMLHttpRequest();
var content = control.audioModel;
var blob = new Blob([content], { type: "audio/mp3"});
formData.append("file", blob);
request.open("POST", "/app/api/upload/audioMessage.php", true);
request.send(formData);
};
Just in case, my uploader php file ( /app/api/upload/audioMessage.php ) is something like this:
<?php
$dest_dir = $_SERVER['DOCUMENT_ROOT'] . '/storage/audio_messages/';
if(!file_exists($dest_dir)) mkdir($dest_dir, 0777);
move_uploaded_file($_FILES['file']['tmp_name'], $dest_dir . uniqid() . ".mp3");
Pay atention to set the audioModel attribute in your audioRecorder directive.

SharePoint 2010 Wiki Template Script Issue

I'm looking for a way to give my SharePoint users a way to create new wiki pages from an existing template. In the process of researching I found a great walkthrough that seems to fit the need (http://www.mssharepointtips.com/tip.asp?id=1072&page=2), but I'm having trouble getting it to work. The problem seems to lie in the assignment of a path to PATHTOWIKI-- if I use "/Weekly Update Wiki", the script returns an error of "There is no Web named '/Weekly Update Wiki'." If I use "Weekly Update Wiki" without the forward slash, I instead get an error of "There is no Web named '/sites/[parentSite]/[childSite]/Weekly Update Wiki/Weekly Update Wiki'."
Any ideas about what I'm not understanding here?
function myCreateProject() {
// Configure these for your environment
// include no slashes in paths
var PATHTOWIKI = "Weekly Update Wiki";
var PATHTOPAGES = "Pages";
// file name only for template page, no extension
var TEMPLATEFILENAME = "Template";
var myPathToWiki = encodeURIComponent(PATHTOWIKI);
var myPathToPages = PATHTOPAGES + "%2f";
var myTemplateFileName = encodeURIComponent(TEMPLATEFILENAME) + "%2easpx";
var EnteredProject = document.getElementById("NewProjName");
var myNewName = EnteredProject.value;
if(myNewName == "") {
alert('Please enter a name for the new project page');
} else {
myNewName = encodeURIComponent(myNewName) + "%2easpx"
$.ajax({
url: PATHTOWIKI + "/_vti_bin/_vti_aut/author.dll",
data: ( "method=move+document%3a14%2e0%2e0%2e4730&service%5fname="
+ myPathToWiki +
"&oldUrl=" + myPathToPages + myTemplateFileName +
"&newUrl=" + myPathToPages + myNewName +
"&url%5flist=%5b%5d&rename%5foption=nochangeall&put%5foption=edit&docopy=true"
),
success: function(data) {
var rpcmsg1 = getMessage(data, "message=", "<p>");
$("#myInfo").append("<br />" + rpcmsg1);
if(rpcmsg1.indexOf("successfully") < 0) {
// get error info
var rpcmsg2 = getMessage(data, "msg=", "<li>");
$("#myInfo").append("<br />" + rpcmsg2 + "<br />");
} else {
$("#myInfo").append("<br />Go to new page<br />");
}
},
type: "POST",
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("X-Vermeer-Content-Type",
"application/x-www-form-urlencoded");
}
});
}
}
Update: I figured out what needed to happen in my case. Since I couldn't get a grasp on the relative approach, I just went with the absolute path for PATHTOWIKI and slightly modified the append in the ajax call.
PATHTOWIKI:
var PATHTOWIKI = "https://[domain]/sites/[parentSite]/[childSite]";
append:
$("#myInfo").append("<br />Go to new page<br />");
The change in the latter line of code is subtle; since I used an absolute path in PATHTOWIKI, I just removed the leading forward slash in the anchor tag, so that <a href=\"/" became <a href=\"". This renders the script slightly less portable, but since it's a one-off effort I'll stick with this unless anything comes along to expand the scope.