Playing Audio File with notification in Tizen - audio

In a Tizen application I want to play an audio file when notification is posted and I have written below code.
function postNotification()
{
try {
var iconPath=tizen.application.getCurrentApplication().appInfo.iconPath;
var myappInfo = tizen.application.getAppInfo();
var myAudio = document.getElementById('myAudio');
var notificationDict = {
content : "Alarm Playing",
iconPath : iconPath,
soundPath : "ab.mp3",
vibration : true,
thumbnails : "icon.png",
ledColor : "#FFFF00",
ledOnPeriod: 10000,
ledOffPeriod : 5000 ,
appId : myappInfo.id };
var myNotification = new tizen.StatusNotification("SIMPLE", "Simple notification", notificationDict);
tizen.notification.post(myNotification);
} catch (err) {
alert(err.name + ": " + err.message);
}
}
The file ab.mp3 is in the same folder with js file. But its not playing that audio. Can anyone help please ?

If it's on the js folder, the path should be:
soundPath : "js/ab.mp3"
Cause the default path is "project root" folder, you have to add the folder name of the resource, as in index.html we do:
<script src="js/main.js"></script>

Related

After upload a media file can not play the file in angular 2, shows 404 not found

I have a problem in Angular2: I have module for media upload (Images/Videos). So upload module is working perfect but after uploading the file when I try to watch the video or view the image file, I get a 404 Not Found error. But if i run ng build and refresh it again I can watch the video or view the image files. Am i doing something wrong or we can handle this with someway?
GET http://localhost:4200/dist/assets/mediauploads/Desktop%20(19).jpg 404 (Not Found)
//This is my node js code
socket.on('Upload', function (data){
var Name = data['Name'];
Files[Name]['Downloaded'] += data['Data'].length;
Files[Name]['Data'] += data['Data'];
if(Files[Name]['Downloaded'] == Files[Name]['FileSize']) //If File is Fully Uploaded
{
fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
var inp = fs.createReadStream("./src/assets/temp/" + Name);
var out = fs.createWriteStream("./src/assets/mediauploads/" + Name);
inp.pipe(out);
inp.on("end", function() {
var path="./src/assets/temp/" + Name;
var tempFile = fs.openSync(path, 'r');
if(fs.existsSync(path)){
fs.closeSync(tempFile);
fs.unlinkSync(path);
socket.emit('Done', {'Image' : './src/assets/mediauploads/' + Name});
}
});
});
}
else if(Files[Name]['Data'].length > 10485760){ //If the Data Buffer reaches 10MB
fs.write(Files[Name]['Handler'], Files[Name]['Data'], null, 'Binary', function(err, Writen){
Files[Name]['Data'] = ""; //Reset The Buffer
var Place = Files[Name]['Downloaded'] / 524288;
var Percent = (Files[Name]['Downloaded'] / Files[Name]['FileSize']) * 100;
socket.emit('MoreData', { 'Place' : Place, 'Percent' : Percent});
});
}
else
{
var Place = Files[Name]['Downloaded'] / 524288;
var Percent = (Files[Name]['Downloaded'] / Files[Name]['FileSize']) * 100;
socket.emit('MoreData', { 'Place' : Place, 'Percent' : Percent});
}
});
When you run ng build the angular app is built into the dist folder. My guess is you have your app setup in such a way you are actually uploading the image into your src/assets folder.
As you are running the app from the dist folder your newly uploaded image/video is not visible. When you rebuild the app the file is copied to the dist folder and becomes accesible.

how to upload a file in vibe.d using the web framework

I am still new to Vibe.d so forgive me if I am missing something obvious.
I want to upload a file in Vibe.d using the web framework. However, all the examples I find, including the one in the book 'D Web Development', are not using the web framework. If I insert the non-web-framework example to my app, it crashes. It would suck if I have to abandon the web framework just for the sake of one feature, which is file upload.
The Vibe.d documentation is a good effort and I appreciate it but until now it is rather sparse and the examples are few and far between.
Here are some snippets of my code:
shared static this()
{
auto router = new URLRouter;
router.post("/upload", &upload);
router.registerWebInterface(new WebApp);
//router.get("/", staticRedirect("/index.html"));
//router.get("/ws", handleWebSockets(&handleWebSocketConnection));
router.get("*", serveStaticFiles("public/"));
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, router);
conn = connectMongoDB("127.0.0.1");
appStore = new WebAppStore;
}
void upload(HTTPServerRequest req, HTTPServerResponse res)
{
auto f = "filename" in req.files;
try
{
moveFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}
catch(Exception e)
{
copyFile(f.tempPath, Path("./public/uploaded/images") ~ f.filename);
}
res.redirect("/uploaded");
}
Can I still access the HTTPServerRequest.files using the web framework? How? Or do I still need it? Meaning, is there another way without using HTTPServerRequest.files?
Thanks a lot!
I have totally forgotten about this question. I remember how frustrating it was when you cannot readily find an answer to a question that seems to be elementary to those who already know.
Make sure you state 'multipart/form-data' in the enctype of your form:
form(method="post", action="new_employee", enctype="multipart/form-data")
Then a field in that form should include an input field of type 'file', something like this:
input(type="file", name="picture")
In the postNewEmployee() method of your web framework class, get the file through request.files:
auto pic = "picture" in request.files;
Here is a sample postNewEmployee() method being passed an Employee struct:
void postNewEmployee(Employee emp)
{
Employee e = emp;
string photopath = "No photo submitted";
auto pic = "picture" in request.files;
if(pic !is null)
{
string ext = extension(pic.filename.name);
string[] exts = [".jpg", ".jpeg", ".png", ".gif"];
if(canFind(exts, ext))
{
photopath = "uploads/photos/" ~ e.fname ~ "_" ~ e.lname ~ ext;
string dir = "./public/uploads/photos/";
mkdirRecurse(dir);
string fullpath = dir ~ e.fname ~ "_" ~ e.lname ~ ext;
try moveFile(pic.tempPath, NativePath(fullpath));
catch (Exception ex) copyFile(pic.tempPath, NativePath(fullpath));
}
}
e.photo = photopath;
empModel.addEmployee(e);
redirect("list_employees");
}
When I tried to learn Vibe.d again, I again became aware of the dearth of tutorials, so I wrote a tutorial myself while everything is fresh as a learner:
https://github.com/reyvaleza/vibed
Hope you find this useful.
Put the upload function inside the WebApp class and use it to handle the form post form(action="/upload", method ="post")
class WebApp {
addUpload(HTTPServerRequest req, ...)
{
auto file = file in req.files;
...
}
}
You can try hunt-framework, Hunt Framework is a high-level D Programming Language Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performance Web applications quickly and easily.
Sample code for action:
#Action
string upload()
{
string message;
if (request.hasFile("file1"))
{
auto file = request.file("file1");
if (file.isValid())
{
// File save path: file.path()
// Origin name: file.originalName()
// File extension: file.extension()
// File mimetype: file.mimeType()
if (file.store("uploads/myfile.zip"))
{
message = "upload is successed";
}
else
{
message = "save as error";
}
}
else
{
message = "file is not valid";
}
}
else
{
message = "not get this file";
}
return message;
}

Electron: get full path of uploaded file

I'm buildind now GUI using Electron. (like PhoneGap for desktop apps)
Is there a way to enable full path for file checked in <input type="file">?
Insted of C:\fakepath\dataset.zip now. (the directory name isn't "fakepath", but that is the value of document.getElementById("myFile").value)
Or, is there other way to select a file?
Electron adds a path property to File objects, so you can get the real path from the input element using:
document.getElementById("myFile").files[0].path
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
const ko = require('knockout')
const fs = require('fs');
const request = require('request-promise');
// replace with your own paths
var zipFilePath = 'C:/Users/malco/AppData/Roaming/Wimpsdata/Wimpsdata.zip';
var uploadUri = 'http://localhost:59887/api/Collector/Upload'
var request = require('request');
request.post({
headers: { 'content-type': 'application/zip' },
url: uploadUri,
body: fs.createReadStream(zipFilePath)
}, function (error, response, body) {
console.log(body);
location.href = 'ScanResults.html';
});
</script>
ASP .NET WebAPI Conontroller
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Wimps.Services.Business;
namespace Wimps.Services.Controllers
{
public class CollectorController : ApiController
{
public async Task<bool> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
Byte[] byteArray = await content.ReadAsByteArrayAsync();
string newFileName = Guid.NewGuid().ToString();
string newFilePath = fileuploadPath + "\\" + newFileName + ".zip";
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
File.WriteAllBytes(newFilePath, byteArray);
string unzipTo = fileuploadPath + "\\" + newFileName;
Directory.CreateDirectory(unzipTo);
DirectoryInfo di = new DirectoryInfo(unzipTo);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
ZipFile.ExtractToDirectory(newFilePath, unzipTo);
return true;
}
catch (Exception e)
{
// handle exception here
return false;
}
}
}
}
Need to add key to web config for file upload
<configuration>
<appSettings>
... other keys here
<add key="FileUploadLocation" value="C:\Temp\Uploads" />
</appSettings>
rest of app config
...
...
It is not possible to do what you are trying for security reasons, according this answer How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?.
However you could do a work around like I did in an electron project I worked on.
Create a HTML button
Then in the renderer process create an event listener to the button you created before.
const ipc = require('electron').ipcRenderer;
const buttonCreated = document.getElementById('button-created-id');
buttonCreated.addEventListener('click', function (event) {
ipc.send('open-file-dialog-for-file')
});
Then in the main process you use the showOpenDialog to choose a file and then send the full path back to the renderer process.
ipc.on('open-file-dialog-for-file', function (event) {
if(os.platform() === 'linux' || os.platform() === 'win32'){
dialog.showOpenDialog({
properties: ['openFile']
}, function (files) {
if (files) event.sender.send('selected-file', files[0]);
});
} else {
dialog.showOpenDialog({
properties: ['openFile', 'openDirectory']
}, function (files) {
if (files) event.sender.send('selected-file', files[0]);
});
}});
Then in the renderer process you get the full path.
ipc.on('selected-file', function (event, path) {
console.log('Full path: ', path);
});
Thus you can have a similar behaviour than the input type file and get the full path.
The accepted answer works great for the original question, but the answer from #Piero-Divasto works a lot better for my purposes.
What I needed was the pathname of a directory which may be rather large. Using the accepted answer, this can block the main process for several seconds while it processes the directory contents. Using dialog.showOpenDialog(...) gets me a near-instant response. The only difference is that dialog.showOpenDialog doesn't take a callback function anymore, and instead returns a promise:
ipcMain.on("open-file-dialog-for-dir", async event => {
const dir = await dialog.showOpenDialog({ properties: ["openDirectory"] });
if (dir) {
event.sender.send("selected-dir", dir.filePaths[0]);
}
});
<script>const electron = require('electron');</script>
<button id="myFile" onclick="this.value=electron.remote.dialog.showOpenDialog()[0]">UpdateFile</button>
Now, the document.getElementById("myFile").value would contain the full path of the chosen file.
As answered by Vadim Macagon:
let { path } = document.getElementById("myFile").files[0]
Since there is no included interface for this for TypeScript as of this answer, to use this you have to cast the File to another type
let { path } = document.getElementById("myFile").files[0] as any
or, if you would rather not use any
interface ElectronFile extends File {
path: string;
}
let { path } = document.getElementById("myFile").files[0] as ElectronFile

VBS to SFTP WinSCP

I am trying to put log files into a SFTP Server. When I try to run I get error Line 1 Char 28 Syntax error. Anyone have any Idea to different code they got working for VBS? Looking for something simple.
cscript Transfer.vbs /type:winscp /SourceFolder:PATH TO LOG DIR /FTPType:sftp /FTPSite: SFTPSITE:PORT /FTPUser:USER /FTPPass:PASS
<job>
<reference object="WinSCP.Session" />
<script language="JScript">
try
{
// Setup session options
var sessionOptions = WScript.CreateObject("WinSCP.SessionOptions");
sessionOptions.Protocol = Protocol_Sftp;
sessionOptions.HostName = "SFTP";
sessionOptions.UserName = "USER";
sessionOptions.Password = "PASS";
var session = WScript.CreateObject("WinSCP.Session");
try
{
// Connect
session.Open(sessionOptions);
// Upload files
var transferOptions = WScript.CreateObject("WinSCP.TransferOptions");
transferOptions.TransferMode = TransferMode_Binary;
var transferResult = session.PutFiles("c:\\Users\PATH TO LOGS\\*", "/", false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
for (var enumerator = new Enumerator(transferResult.Transfers); !enumerator.atEnd(); enumerator.moveNext())
{
WScript.Echo("Upload of " + enumerator.item().FileName + " succeeded");
}
}
finally
{
// Disconnect, clean up
session.Dispose();
}
}
catch (e)
{
WScript.Echo("Error: " + e.message);
WScript.Quit(1);
}
</script>
</job>`
So I just had to install the SDK for Windows machine. Register the .dll file that winscp gives you. Also register via Com as well. Thakn you for looking into it

Create an archive and add files in it before sending to client

I'd like to create an archive with archiver and put some files in it. Client's side, an user will click on a button and it'll generate the archive (server's side).
I'm using Express.js, this is my server side code where the archive will be generated. I did something like this :
app.get('/export/siteoccupancy', function(req,res){
if(_.isEmpty(req.query)){
res.status(404).send('requires a start and end date');
}else{
//getting paramas
var sDate = req.query.startDate;
var eDate = req.query.endDate;
}
var fs = require('fs');
var archiver = require('archiver');
var archive = archiver('zip');
archive.on('err',function(err){
res.status(500).send({error : err.message});
});
res.on('close',function(){
console.log('Archive size : %d b',archive.pointer());
return res.status(200).send('OK').end();
});
res.attachment('data-export.zip');
archive.pipe(res);
var stream = fs.createWriteStream("data-report.txt')");
stream.once('open',function(fd) {
stream.write('test1');
stream.write('\n test2');
stream.write('\n test3');
stream.end();
});
archive.append(stream);
archive.finalize();
});
This is totally new for me and I'd like to understand why the console tells me the stream file is empty ?
Error: append: entry name must be a non-empty string value
at Archiver.append
Regards
you can only append a readStream, because an archive can only take data from readstreams. You can use the method named archive.append, and you should pass as a second argument with the name property to name the file. Like so :
archive.append(myReadStream,{ name : 'myTest.txt'});

Resources