Get filename from URL without it in JavaScript - javascript

How can I get the filename from a given URL in PhoneGap?
In JavaScript, I used something like this:
var uri = encodeURI("http://www.openerpspain.com/descargas-documentacion?download=2");
My application downloads the file, but I have to manually set the file name. To illustrate, when I call
onclick="descarga('http://www.openerpspain.com/descargas-documentacion?download=2')"
this function is run:
function descarga(URL){
var rutaarchivo = "file:///sdcard/data/com.protocolo/test1.pdf";
alert(rutaarchivo);
var filetransfer = new FileTransfer();
filetransfer.download(URL, rutaarchivo,
function(entry){
alert("Download complete : " + entry.fullPath);
},function(error) {
alert("download error source " + error.source);
});
}
This saves the download to ../com.protocolo, and its filename is test.pdf. I want to be able to save it as the name it is set as on the server (*manual_openerp.230209.pdf*) at the real URL, *...//www.openerpspain.com/descargas/manual_openerp.230209.pdf*.
How do I do that?

String fileName = url.substring(url.lastIndexOf('/') + 1);
where url is the complete path of your file.

Use:
url="file:///sdcard/data/com.protocolo/test1.pdf?getVar=value";
url.replace(/\?.*$/,"").replace(/.*\//,"");

This is basically asking How to get the file name from a full path using JavaScript?. Here, the solution was:
var filename = url.replace(/^.*[\\\/]/, '');

I added in my URLs parameters. Then in PhoneGap I used:
function getParameterByName( name,href ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Called from :
var filename = getParameterByName ("nombrefichero", url);
So this way I can get example.pdf from:
http://www.download.com/fake/example.pdf?nombrefichero=example.pdf
And then I can download it, and save it where I want.

Related

How can I pass a value in a URL and insert value in a new URL to redirect with Javascript?

I am passing a value in a URL in the form of http://example.com/page?id=012345. The passed value then needs to be inserted in a new URL and redirect the page to the new URL. Here is what I have been working with
function Send() {
var efin = document.getElementById("id").value;
var url = "https://sub" + encodeURIComponent(efin) + ".example.com" ;
window.location.href = url;
};
Sounds like you're looking for the features of URLSearchParams - Specifically using .get() to fetch specific parameters from the URL
// Replacing the use of 'window.location.href', for this demo
let windowLocationHref = 'http://example.com/page?id=012345';
function Send() {
let url = new URL(windowLocationHref);
let param = url.searchParams.get('id');
let newUrl = "https://sub" + encodeURIComponent(param) + ".example.com" ;
console.log('Navigate to: ' + newUrl);
//window.location.href = newUrl;
};
Send();

Java net url refused connection

I'm working with ARIS tool and I want to make calls(GET, POST...) in ARIS to ARIS API repository!
I have authentication that works when I try it directly in the repository, but I got an error when I debug the code I have in ARIS.
The error: Error running script: Connection refused: connect.
I have the following code:
var obj = new java.net.URL(url);
var con = obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", java.net.USER_AGENT);
var tenant = "";
var name = "";
var password = "";
var key = "";
var authString = tenant + ":" + name + ":" + password + ":" + key;
var encoder = new java.lang.String(Base64.encode(authString));
con.setRequestProperty("Authorization", "Basic" + encoder);
var responseCode = con.getResponseCode();
var iN = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
var inputLine = new java.lang.String();
var response = new java.lang.StringBuffer();
while((inputLine = iN.readLine()) != null){
response.append(inputLine);
}
iN.close();
return new java.lang.String(response);
Is the problem that I use Basic authentication, but I have tenant and key also or it's something else?
Also, name, password, key and tenant I'm leaving empty for security purposes, but in the original code the values are inserted. Also the url parameter contains the url link that is called directly in the repository.
Can someone please help me?
Thanks!

Google script xls attachment not displaying

any thoughts as to why this script emails an attachment but the attachment is not the correct spreadsheet, and looks like some sort of google error page.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
Logger.log(url);
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("youremail#email.com", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
I guess API has changed. You can try Drive REST API(v3) instead. Replace
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
var params = { ... };
var blob = UrlFetchApp.fetch(url, params).getBlob();
to
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() +
"/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" +
"{your API key}";
var blob = UrlFetchApp.fetch(url).getBlob();
I tested and it worked. Of course you first should get your own API key, etc, at API Manager. Then you can try some APIs like simple GET requests at APIs Explorer. Or you can try some APIs, in this case Files: export, also at the documentation page itself, but notice that you cannot try your own API key here.
This is the updated code that #sangbok helped with:
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var sheet = DriveApp.getFileById(ss.getId());
// sets sharing to public - to send out email.
sheet.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" + "YOURAPIKEYGOESHERE4";
var blob = UrlFetchApp.fetch(url).getBlob();
Logger.log(url);
blob.setName(ss.getName() + ".xlsx");
var now = new Date();
MailApp.sendEmail("YOUREMAILADDRESSGOESHERE", "EMAIL SUBJECT " + now , "EMAIL BODY " + now , {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
// returns the file back to Private access
sheet.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.EDIT);
}

fs readFilesync error path must be a string

i have a code for uploading file
here the code :
var oriPath = JSON.stringify(req.files.profilePicture);
var data = fs.readFileSync(oriPath.path);
var ext = path.extname(oriPath.name);
if (!ext) {
return next(err);
}
var newName = Date.now().toString() + ext;
var path = config.fullhostname + config.uploadDir + newName;
if (!fs.writeFileSync(path, data)) {
return next("Failed to upload image", 400)
}
and showing error like this : uncaughtException TypeError: path must be a string refers to var data = fs.readFileSync(oriPath.path);
but the file is successfuly uploaded, how to fix that? thank you
try to force string conversion:
var data = fs.readFileSync(String(oriPath.path))

how to do mulitpart request from cordova

I have to submit form with an image + some additional form fields (mulitipart form submission request).
I have tried this
function upload() {
var img = document.getElementById('image');
var imageURI = img.value;
var options = new FileUploadOptions();
options.fileKey = "photo";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
var params = new Object();
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "https://www.example.com/upload.php", win, fail,
options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
html is
<input type="file" id="userImage" name="photo">
but it is returning error code 1
and image path is fakepat\1089001
it is also not getting picture name instead a number is showing?
so how do i get image path from input text box?
If i hard code the image (only for testing) in src then request
error code 1
undefined varailbe image
Remember i have to submit image in base64 url
Additional form data would be sent in your params object. Yours is blank now, but you could do
options.params.formkey1 = value1;
options.params.formkey2 = value2;
As for your second question (and I'd try to keep things limited to one question at a time), you need to pass the path of the file on the device. See the docs for File Transfer.
Finally, you don't need to use base64 to upload the data. I'd avoid that as it is bigger than binary data. Just let FileTransfer push up the binary data. It was built to do so.

Categories