I am new to JavaScript. I am working with a website. In this website i have provide a functionality to the users to download a file. Now i need to know is there any way to send those downloaded file to email. My code for downloading content is given below.
function download2(data, filename, type) {
var file = new Blob([data], { type: type });
if (window.navigator.msSaveOrOpenBlob)
window.navigator.msSaveOrOpenBlob(file, filename);
else {
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
};
and my send mail function is given below:
function sendMail(mail, name, roll, cls, sec, grp) {
var link = "mailto:" + mail
+ "?cc=ictpracticalslc#gmail.com"
+ "&subject=" + escape("AnswerSheet Submitted By " + name + " Class " + cls + " Section " + sec + " Group " + grp)
+ "&body=" + escape("My Roll Is " + roll)
;
window.location.href = link;
};
when i call download2("<p>Hello</p>", "hello.html", "text/plain"). A file named hello.html is downloaded in my local machine. But i need to attach this file in sendMail function. so that users can send email with this attachment.
I need to update the sendMail function so that it can accept an attachment which is downloaded by download2 function.
I am badly need this functionality. I am stuck here for 15 days and find no suitable solution. I need to do this with only javascript or jquery.
Related
I am working on ionic framework for android .
It simply contains an Iframe to embed a website in a blank project.
This is the website http://www.ultrayoutube.com/ANDROID/#/wanna.
I am facing two problems
Making Iframe equal to size of screen
I want Iframe to be equal to the size of window . I am using <iframe src="http://www.ultrayoutube.com/ANDROID/#/wanna" style="width:100%; height:100%;" ></iframe>
But iframe only takes 1/2 of screen in emulator
When the user searches for the song he must be able to download it by clicking download mp3
I have gone through some plugins as file transfer plugins but they all need a download link to download something . I want it that when the user clicks on button download mp3 , that link is automatically passed to the plugin and is downloaded to user's cell phone .
on Document Head try to initialise your file transfer plugin
function onDeviceReady() {
console.log('deviceready');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
window.fs = fileSystem;
window.fileTransfer = new FileTransfer();
window.fileTransfer.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
console.log(perc + '%');
$('.progress-bar').css({width: perc + '%'});
}
};
window.fs.root.getDirectory('Download', {create: true}, function(dirEntry) {
window.downloadFolder = dirEntry;
});
},
function(evt) {
console.log(evt.target.error.code);
}
);
}
Change : script.js
app.run(function($rootScope, downloader, alertService) {
$rootScope.fs = window.fs;
$rootScope.downloadFolder = window.downloadFolder;
$rootScope.fileTransfer = window.fileTransfer;
$rootScope.messages = {}
...
$rootScope.saveContent = function(url) {
var uri = encodeURI(url);
$rootScope.fileTransfer.download(
uri,
$rootScope.downloadFolder.toURL() + "/" + url.substring(url.lastIndexOf('/') + 1),
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
}
);
};
...
I have a function in my Apache Cordova application to create a new list item inside a sharepoint list, and I was wondering if it was possible to add an image to this new item, this would come as an 'attachment' in the sharepoint list. My function to add a new item looks like this:
function CreateItem(Title, Description) {
var soapEnv =
"<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soapenv:Body>" +
"<UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>LISTNAME</listName>" +
"<updates>" +
"<Batch OnError=\"Continue\">" +
"<Method ID=\"1\" Cmd=\"New\">" +
"<Field Name=\"ID\">New</Field>" +
"<Field Name=\"Title\">" + Title + "</Field>" +
"<Field Name=\"Description\">" + Description + "</Field>" +
"</Method>" +
"</Batch>" +
"</updates>" +
"</UpdateListItems>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
$.ajax({
url: "URL",
type: "POST",
dataType: "xml",
data: soapEnv,
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction",
"http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
complete: processCreateResultSuccess,
contentType: "text/xml; charset=\"utf-8\"",
error: processCreateResultError
});
}
The image is taken with the Cordova app and has the ID "image". Any thoughts?
SharePoint: AddAttachment SOAP Web Service
Yes, you can use SharePoint SOAP web services to upload an image attachment to a list. However, there are some limitations.
My demo below uses the AddAttachment action of the Lists web service. The required parameters are listed and can be modified for your own environment. The demo simply adds a text file attachment, but it works with images and other file types too. Also works with SP 2007-2013.
The limitation is that files must be encoded as base-64 for transfer within the SOAP envelope. On the client side, base-64 file encoding is not a trivial task. I've done it using the FileReader object, but that is only available in modern browsers (IE10). There might be other options with mobile devices, but I've not researched it. Alternatively, you might look at the newer REST API.
<html>
<body>
<script type='text/javascript'>
function addAttachment( ) {
var webUrl = '', // base url when list in sub site
listName = 'CustomList', // list name or guid
listItemID = '1', // list item id
fileName = 'HelloWorld.txt', // file name
attachment = 'SGVsbG8gV29ybGQ=', // base-64 encode file data "Hello Word!"
xhr, soap;
soap = (
'<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope '+
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '+
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" '+
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">'+
'<listName>' + listName + '</listName>'+
'<listItemID>' + listItemID + '</listItemID>'+
'<fileName>' + fileName + '</fileName>'+
'<attachment>' + attachment + '</attachment>'+
'</AddAttachment>'+
'</soap:Body>'+
'</soap:Envelope>'
);
xhr = new XMLHttpRequest();
xhr.open( 'POST', webUrl + '/_vti_bin/Lists.asmx', true );
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/sharepoint/soap/AddAttachment');
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
// do something - returns file path or error message
console.info( xhr.status + '\n' + xhr.responseText );
}
xhr.send( soap );
}
</script>
</body>
</html>
What I'd like to do is
get the URI of a video file on the device via cordovas javascript API
set the URI as value of a HTML5 video tag's src attribute.
The second part shouldn’t be a problem.
Concerning the first task, there are a lot of good structured tutorials like Raymond Camden's demonstrating how to get local files through javascript in an cordova environment.
However, with the newest version of cordova, I could not get it to work.
The video file
The video is located either in assets/www/videos/testvid.webm or res/raw/testvid.webm in the built apk file. Both variations did not work.
The javascript
myPath = cordova.file.applicationDirectory; // -> file:///android_asset/
//myPath += "www/videos/testvid.webm";
respectively
myPath = cordova.file.applicationStorageDirectory; // -> file:///data/data/com.example.MyPackage/
//myPath += "raw/testvid.webm";
Then:
window.resolveLocalFileSystemURL(myPath, gotFile, fail);
function gotFile(entry){
if(entry.isDirectory)
alert JSON.stringify(entry.getFile("testvid.webm"));
}
The permissions
In res/xml/config.xml access permissions are added
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,root" />
The error is {code:1} -> NOT_FOUND_ERR
What am I doing wrong? How to navigate to the file, or where can one put it to be found?
I figured it out!
There is a bug in the android version of the cordova file plugin.
A workaround is transferring the file(s) from the assets directory of the app itself file:///android_asset/ (cordova.file.applicationDirectory) to a working directory on the phone like file:///data/data/com.example.MyPackage/files (cordova.file.dataDirectory). Then set the video's source URL to this new file.
XMLHttpRequest as well as FileTransfer will do the trick.
var myFilename = "testvid.webm";
var myUrl = cordova.file.applicationDirectory + "www/videos/" + myFilename;
var fileTransfer = new FileTransfer();
var filePath = cordova.file.dataDirectory + myFilename;
fileTransfer.download(encodeURI(myUrl), filePath, (function(entry) {
/*
res = "download complete:\n"
res += "fullPath: " + entry.fullPath + "\n"
res += "localURL: " + entry.localURL + "\n"
alert(res += "nativeURL: " + entry.nativeURL + "\n")
*/
var vid = document.getElementById("someID");
vid.src = entry.nativeURL;
vid.loop = true;
}), (function(error) {
alert("Video download error: source " + error.source);
alert("Video download error: target " + error.target);
}), true, {
headers: {
Authorization: "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
});
I'm trying to write a JS Windows app. I have a button on the first page, and the click event handler code is as follows:
function pickSingleAudioFile(args) {
document.getElementById("output").innerText += "\n" + this.id + ": ";
// Create the picker object and set options
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.musicLibrary;
openPicker.fileTypeFilter.replaceAll([".mp3"]);
// Open the picker for the user to pick a file
openPicker.pickSingleFileAsync().then(function (file) {
if (file) {
// Application now has read/write access to the picked file
WinJS.log && WinJS.log("Picked file: " + file.name, "sample", "status");
document.getElementById("output").innerText += "You picked " + file.name + " from " + file.path;
// Save the file as an audio tag and load it
var audtag = document.createElement('audio');
audtag.setAttribute("id", "audtag");
audtag.setAttribute("controls", "true");
audtag.setAttribute("msAudioCategory", "backgroundcapablemedia");
audtag.setAttribute("src", "\"" + file.path + "\"");
document.getElementById("output").appendChild(audtag);
audtag.load();
} else {
// The picker was dismissed with no selected file
WinJS.log && WinJS.log("Operation cancelled.", "sample", "status");
}
});
}
The path is something like "D:\Songs\song1.mp3" or "\network-share\My Music\song name.mp3" I get the "Invalid Source" error when trying to load the file.
At first glance, this:
audtag.setAttribute("src", "\"" + file.path + "\"");
should instead be this:
audtag.setAttribute("src", file.path);
It's not clear why you are adding the backslashes. However, depending on what you are doing and based on samples I've seen, you'd be better off doing something like this:
var fileLocation = window.URL.createObjectURL(file, { oneTimeOnly: true });
audtag.setAttribute("src", fileLocation);
You might check out the "Playback Manager msAudioCategory Sample" from the Windows Dev Center for more ideas.
I'm using a plugin to generate a csv file from a table, the file is being downloaded with a "download" filename, how can I change the filename e.g. as dowload.csv
var csv = $("#table").table2CSV({delivery:'download'});
window.location.href = 'data:text/csv;charset=UTF-8,'+ encodeURIComponent(csv);
i wrote a tool you can use to save a file to the downloads folder of the local machine with a custom filename, if that's possible on the client's machine.
as of this writing, you need chrome, firefox, or IE10 for that specific capability, but this tool falls-back to an un-named download if that's all that's available, since something is better than nothing...
for your use:
download(csv, "dowload.csv", "text/csv");
and the magic code:
function download(strData, strFileName, strMimeType) {
var D = document,
a = D.createElement("a");
strMimeType= strMimeType || "application/octet-stream";
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([strData], {type: strMimeType}), strFileName);
} /* end if(navigator.msSaveBlob) */
if ('download' in a) { //html5 A[download]
a.href = "data:" + strMimeType + "," + encodeURIComponent(strData);
a.setAttribute("download", strFileName);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
a.click();
D.body.removeChild(a);
}, 66);
return true;
} /* end if('download' in a) */
//do iframe dataURL download (old ch+FF):
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + strMimeType + "," + encodeURIComponent(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
} /* end download() */
update: added future-resistant IE routine
update2: checkout the evolved version on GitHub that includes dataURL and Blob support.