hey i am creating a app in which dynamic images should be download from the net but some cant able to download kindly check the code below and give some suggestion to download and also tell how to pass dynamic image link in social share plugin in ngcordova .
$
scope.downloadImage = function() {
$http.get('http://sabkideal.com/phpapi_/cashback.php').success(function(response) {
$scope.data = response;
for (var i=0 ;i <response.length; i++)
{
var url = response[i].image;
var deal = response[i].id;
//url showing the same url every time i click and not jumping to next statement when click on send image download .
console.log(deal);
console.log(url);
var filename = url.split("/").pop ;
console.log(filename);
var targetPath = encodeURI(cordova.file.dataDirectory + fileName);
console.log(targetPath);
var options = {};
var trustHosts = true;
}
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(
function(result) {
alert('Download success');
refreshMedia.refresh(targetPath);
},
function(err) {
alert('Error: ' + JSON.stringify(err));
},
function(progress) {
// progressing download...
})
});
}
Related
I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/
I am trying to download different sections of a page as jpeg. There are two ways I'm going about it; One is to include a download button in every section and when it is clicked, the section is downloaded as jpeg; The other is to include a button atop the page and when it is clicked, all the sections are downloaded.
The download section by section code works well but the issue arises when I try to do the download all option, It downloads files of type file instead of jpeg pictures.
When I logged the url I'm supposed to download from, I find out that it is empty but it isn't inside the html2canvas function.
I am using html2canvas to convert html to canvas and JSZip to zip it.
function urlToPromise(url) {
return new Promise(function(resolve, reject) {
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
reject(err);
} else {
resolve(data);
console.log(data);
}
});
});
}
function getScreen(){
var caption = $('#caption-input').val();
var allSections = $("#content").children().unbind();
var allSectionsArray = $.makeArray(allSections);
console.log(allSectionsArray);
var zip = new JSZip(); //Instantiate zip file
var url = "";
for(var i = 0; i < allSectionsArray.length; i++){
console.log("Currently at " + allSectionsArray[i].id);
var queryId = allSectionsArray[i].id.toString();
html2canvas(document.querySelector("#"+queryId)).then(function(canvas) {
$("#blank").attr('href',canvas.toDataURL('image/jpeg', 1.0));
$("#blank").attr('download',caption + ".jpeg");
//$("#blank")[0].click();
url = $("#blank").attr('href');
console.log(url);
});
console.log(url);
var filename = "image " + (i+1);
zip.file(filename, urlToPromise(url),{binary:true}); //Create new zip file with filename and content
console.log('file ' + (i+1) + ' generated');
console.log(filename+ "\n" + url);
}
//Generate zip file
generateZipFile(zip);
}
function generateZipFile(zip){
zip.generateAsync({type:"blob"})
.then(function callback(blob) {
saveAs(blob, "example.zip");
console.log("zip generated");
});
}
Following is my code which upload files on server using dropzone.js plugin:
var file_up_names = new Array;
var duplicate_files = new Array;
var token = $('input[name=_token]').val();
Dropzone.autoDiscover = false;
var dropzone = $("#addPhotosForm").dropzone({
addRemoveLinks: true,
dictRemoveFileConfirmation: "Do you want to remove this image?",
dictDefaultMessage: "Drop images here to upload",
dictRemoveFile: "Remove photo",
init: function() {
this.on("success", function(file, response) {
if (response.status === 1) {
file_up_names.push(response.filename);
$(file.previewTemplate).append('<span class="server_file_path hide">' + response.newfilename + '</span>');
} else if (response.status === 2) {
duplicate_files.push(response.filename);
this.removeFile(file);
}
}),
this.on("queuecomplete", function() {
var html = "Photos added successfully!";
$('#photoUploadSuccess').html('');
$('#photoUploadError').html('');
$('#photoUploadSuccess').removeClass('hide');
$('#photoUploadError').addClass('hide');
if (file_up_names.length > 0) {
if (duplicate_files.length > 0) {
html += " Following photos are skipped as those are already uploaded.";
html += "<ul>";
for (var i = 0; i < duplicate_files.length; ++i) {
html += "<li>";
html += duplicate_files[i];
html += "</li>";
}
html += "</ul>";
}
$('#photoUploadSuccess').html(html);
} else if (duplicate_files.length > 0 && file_up_names.length === 0) {
html = "Following photos already exists. Please check to see if it already exists and try again.";
html += "<ul>";
for (var i = 0; i < duplicate_files.length; ++i) {
html += "<li>";
html += duplicate_files[i];
html += "</li>";
}
html += "</ul>";
$('#photoUploadSuccess').addClass('hide');
$('#photoUploadError').removeClass('hide');
$('#photoUploadError').html(html);
} else {
html = "Photos not uploaded!";
$('#photoUploadSuccess').addClass('hide');
$('#photoUploadError').removeClass('hide');
$('#photoUploadError').html(html);
}
duplicate_files = [];
file_up_names = [];
setTimeout(function() {
$('#photoUploadSuccess').html('');
$('#photoUploadError').html('');
$('#photoUploadSuccess').addClass('hide');
$('#photoUploadError').addClass('hide');
}, 5000);
}),
this.on("removedfile", function(file) {
var server_file = $(file.previewTemplate).children('.server_file_path').text();
// Do a post request and pass this path and use server-side language to delete the file
var token = $('input[name=_token]').val();
$.ajax({
type: 'POST',
headers: {'X-CSRF-TOKEN': token},
url: "{{ URL::route('removePhotos') }}",
data: "file_name=" + server_file,
dataType: 'html'
});
})
}
});
While below is my server code which get file's md5 and store it on server and next time when user upload same image again it check in database and if same md5_file result found it won't allow to upload image. It work when i use simple form, but on dropzone it's not working:
$tempFile = $_FILES['file']['tmp_name'];
$md5_check = md5_file($tempFile);
//check if same image uploaded before
$duplicateCheck = Photos::where('userId', '=', $this->userId)->where('md5_check', '=', "$md5_check")->where('isDeleted', '=', 0)->count();
I've found that if I upload same images together it won't work and return count 0 from DB. But if I upload same images separately like for example upload image once it uploads, upload same image again it get count from DB and give message that image already there. Maybe it's due to dropzone asynchronous calls but can't figure it out how to handle this.
It's because when you upload more than one image $_FILES contains an array of files, so you should cycle it with a foreach and do your operations inside that loop.
You can check what's happening when you upload more than 1 files by inserting this line of code:
var_dump($_FILES);
Or if you want a result better readable:
echo "<pre>".print_r($_FILES, true)."</pre>";
Check the structure of $_FILES when you upload more than 1 file, it should be an array of files.
I have the following JS that is run using phantomjs.
var webPage = require('webpage');
var system = require('system');
var page = webPage.create();
page.customHeaders = {
"pragma": "akamai-x-feo-trace"
};
if (system.args.length === 1) {
console.log('Try to pass some args when invoking this script!');
} else {
page.open(system.args[1], function (status) {
var content = page.content;
console.log('Content: ' + content);
phantom.exit();
});
}
I wanto to save the output of console.log('Content: ' + content); to a folder with ./html/<random#>.html.
How should I go about it?
It seems that you only want to save the page content. You can use the Filesystem module to write the content to a file. A random filename can be generated by invoking ''+(Math.random()*100000000000000000)+'.html'.
Below is my server code where I try to get the file that was uploaded. However, fs.writeFiledoesn't work, so I'm assuming that I'm doing something wrong.
server.on('request', function(request, response){
....
if((pathArray[1] == "photos") && (pathArray[2] = "new")){
var imagesPath = './images';
uploadPhoto(response, imagesPath);
}
else if(path == '/document/save'){
console.log("path: " + path);
var body = '';
request.on('data', function(data){
body += data;
});
request.on('end', function() {
var note = querystring.parse(body);
console.log("Body data: " + note);
var newPath = "./images/myimage.jpg";
fs.writeFile( newPath, body, function (err) {
if (err) throw err;
});
});
}
Here is my HTML for the form, if it helps anyone:
function uploadPhoto(response, imageLoc){
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.write('<html><body>');
response.write('<div class="uploadFile">');
response.write('<link rel="stylesheet" type="text/css" href="style.css">');
response.write('<form action =/document/save>');
response.write('<method = "post">');
response.write('<enctype="multipart/form-data">');
response.write('<label for="name">Upload new photo</label>');
response.write('<br></br>');
response.write('<input type="file" name="name">');
response.write('<br></br>');
response.write('<button type="submit">Upload</button>');
response.write('</div>');
response.write('</body></html>');
response.write('</form>');
response.end();
}
After I upload the file, url goes to /document/save/uploadImage.jpg. But when I try to read the content of the image ("body") to save the image into a folder and then display it, seems that the content of the object of the request is empty.
How do I get the content of the image using node.js without express, or any other external libraries than what I have? Is fs.writeFile a good function to use when writing a binary file?
What has to be taken into consideration is the fact that the received data from the upload has this sort of format:
------WebKitFormBoundary9BhXe3lt2UddCDz9
Content-Disposition: form-data; name="document"; filename="globeSS.jpg"
Content-Type: image/jpeg
ÿØÿà JFIF d d ÿì Ducky d ÿá
//[binary binary binary...]
Ï[leñnœ“}ÛOyŠVÑ0êãXÂ}Ö'±”É iÉöÚ$GTQ7äŽø
uÚ_êÍòXgV¿Õ=€q`]aKRÐÀ
ò<ÿÙ
------WebKitFormBoundary9BhXe3lt2UddCDz9--
To get the binary data only( and thus the file), the programmer has to figure out a way to clip the binary out of that data. In the below code, binary of the picture is all saved in memory, so if the user uploads a particularly large file, the following implementation might fail. It'd be best to try to write down the file in chucks.
request.setEncoding('binary');
//Grabbing all data from the image
var body = ''
var binaryEnd; //gets the string that indicates the location of the end of the binary file
var first = true;
request.on('data', function(data) {
if(first)
binaryEnd = data.toString().substring(0, data.toString().indexOf('\n')-1);
first = false;
body += data
});
//Dealing with the image once we have everything
request.on('end', function() {
var note = querystring.parse(body, '\r\n', ':')
console.log(note)
//making sure than an image was submitted
if (note['Content-Type'].indexOf("image") != -1)
{
//get the filename
var fileInfo = note['Content-Disposition'].split('; ');
for (value in fileInfo){
if (fileInfo[value].indexOf("filename=") != -1){
fileName = fileInfo[value].substring(10, fileInfo[value].length-1);
if (fileName.indexOf('\\') != -1)
fileName = fileName.substring(fileName.lastIndexOf('\\')+1);
console.log("My filename: " + fileName);
}
}
//Get the type of the image (eg. image/gif or image/png)
var entireData = body.toString();
var contentTypeRegex = /Content-Type: image\/.*/;
contentType = note['Content-Type'].substring(1);
//Get the location of the start of the binary file,
//which happens to be where contentType ends
var upperBoundary = entireData.indexOf(contentType) + contentType.length;
var shorterData = entireData.substring(upperBoundary);
//replace trailing and starting spaces
var binaryDataAlmost = shorterData.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
//Cut the extra things at the end of the data (Webkit stuff)
var binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf(firstLine));
//Write to a file
fs.writeFile('./images/' + fileName , binaryData, 'binary', function(err)
{
//forward to another location after writing data
response.writeHead(302, {
'location':'/index.html'
});
response.end();
});
}
else
respond(404, "Please input an image", response);
});
This should work in all browsers (please note that internet explorer does not limit its data with ------WebkitFormBoundary, but something else (I think only -----, but I forgot.)