I am working phonegap + rest webservice. The service given below is working gud with web application test. the image file was uploaded in the local webserver. But same service is not working in phonegap. Included both codes here.
RestWebService
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("image") InputStream uploadedInputStream,
#FormDataParam("image") FormDataContentDisposition fileDetail) {
System.out.println("entered");
//some logic .. this method is working good using webapplication ... i tested using html page
}
Phonegap code
function myDetails()
{
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imgByte.substr(imgByte.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imgByte, IMGURL, win, fail, options);
alert("finished calling upload");
}
function win(r) {
alert("success");
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);
}
New some guidance
Log cat error :
04-18 18:30:31.621: E/FileTransfer(9459): {"target":"http:\/\/10.1.6.88:8080\/TodaysAdminAds\/resources\/service\/vendor\/vendorregistration","source":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P\/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P\/wAARCAHgA9QDASIAAhEBAxEB\/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL\/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJyt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GOlFADvpxS5HqM0mMHgUpB7UAJjsBTTwTngdqdikOM4zzQAflmlAyOf5UmewPXpxSK\/B4Kn0NADj6dDRwOgo79qTtgnHXnuKAEyC3APoTjOKACvIyfU9qOO3APfFCqFyAe\/ftQA4gntS845\/lTcBsqVyp4P0pk
Related
Please help me to resolve this issue, am try to solve this from last week. Using cordova file transfer plugins am try to upload my image to production server
however am getting error code 1.
i checked source and target path both are accessible. Please find my cordova setup versions.
Cordova -> 7.1.0, Phonegap -> 7.1.1, cordova-plugin-file-transfer-> spec=1.7.1
Code:
function staticpathu_upload() {
var fileURL = 'https://example.com/Al_2_1518090802.jpg';
var uri = encodeURI('https://example.com/dummy.php');
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(fileURL, uri, onSuccess, onError, options);
function onSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function onError(error) {
console.log(error);
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
Error:
FileTransferError {
code: 1,
source: "https://example.com/Al_2_1518090802.jpg",
target: "https://example.com/dummy.php",
http_status: null,
body: null,
}
This issue with ServerUrl, its not allowing me to post the image to server. I have created dummy.php on server root folder and execute from below code its working fine. It won't work from desktop we have check in mobiles or emulators only.
function uploadphoto(){
navigator.camera.getPicture(uponSuccess, uponFail, { quality: 50,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
destinationType: Camera.DestinationType.FILE_URI
});
// Change image source and upload photo to server
function uponSuccess(imageURI) {
// Set image source
var image = document.getElementById('fileuploadimg');
$$('.gAlbumList').append('<img src="'+imageURI + '?' + Math.random()+'" />');
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "https://example.com/dummy.php", function(result){
$$('.error').append('<p>successfully uploaded ' + result.response+'</p>');
}, function(error){
$$('.error').append('<p>error : ' + JSON.stringify(error)+'</p>');
}, options);
}
function uponFail(message) {
$$('.error').append('<p>Failed because: ' + message+'</p>');
}
fileUrl must be a
Filesystem URL representing the file on the device or a data URI. For backwards compatibility, this can also be the full path of the file on the device. (See Backwards Compatibility Notes below)
See the docs
This is propably the reason why a FileTransferError.FILE_NOT_FOUND_ERR (error code 1) is thrown.
I want to connect to my web socket that put on amazone instance with some ip. I can connect my web socket with some ip and port with google rest client app and its working very well.
Screen Shot :
But if i want to connect this with java script it can not connect. This is working fine before 2-3 month. i have not change and thing but its not working now.
If i want to connect with firefox it produce an error.
Here is my code :-
function init() {
var host = "ws://XX.XX.XXX.XXX:XXXX"; // SET THIS TO YOUR SERVER
try {
var socket = new WebSocket(host);
// alert('WebSocket - status ' + socket.readyState);
log('WebSocket - status ' + socket.readyState);
socket.onopen = function (msg) {
alert('open');
alert("Welcome - status " + this.readyState);
log("Welcome - status " + this.readyState);
if (this.readyState != 1)
{
reconnect();
}
};
socket.onmessage = function (msg) {
// alert("Received: " + msg.data);
log("Received: " + msg.data);
};
socket.onclose = function (msg) {
// alert("Disconnected - status " + this.readyState);
log("Disconnected - status " + this.readyState);
};
} catch (ex) {
alert(ex);
log(ex);
}
$("msg").focus();
}
This is alerting status 0 and error show in console :-
Firefox can't establish a connection to the server at ws://XX.XX.XXX.XXX:XXXX.
var socket = new WebSocket(host);
I'd try your code and for me is working just fine, I'd test it with this webpage: https://www.websocket.org/echo.html , maybe could be helpful for testing purposes. But also i found this question: websocket-rails, websocket handshake error , maybe also help.
However i'd just change the host in your code to this:"ws://echo.websocket.org", and everything works without problems.
Hope you find a solution and that this info was of any help. Here's your code that i used for the test:
function init() {
var host = "ws://echo.websocket.org";
try {
var socket = new WebSocket(host);
alert('WebSocket - status ' + socket.readyState);
socket.onopen = function (msg) {
alert('open');
alert("Welcome - status " + this.readyState);
if (this.readyState != 1)
{
reconnect();
}
};
socket.onmessage = function (msg) {
alert("Received: " + msg.data);
};
socket.onclose = function (msg) {
alert("Disconnected - status " + this.readyState);
};
} catch (ex) {
alert(ex);
}
$("msg").focus();
}
*Sorry for my bad english.
I need to detect whether an specific .js file was served in a http response and additionally, check the domain it came from, like this:
I need to automatically detect the lack of the js file and email the incidence
I tried Net::Http, rest-client, mechanize and a lot of gems, they just return the html header. It seems I need to monitor http traffic with tools like PhantomJS and checking for the file, but is there any rubyesque way of doing this?
Thanks in advance
I ended with the phantomjs approach. A ruby script iterate over a database table and then calls this phantomjs script for each record representing an URL
This is the phantomjs script
var page = require('webpage').create(),
system = require('system'),
address,
isScript = false;
var fs = require('fs');
// main
analizePage(system.args[1]);
//open page.
//onResourceRequested event, compares domain of each one with 'my.domain.net'
//append to a log file: -1 for failed url, 1 for script presence, 0 for no script presence
function analizePage(address){
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address ' + address);
fileWriter(-1, address);
}
else
{
if (!isScript){
fileWriter(0, address);
}
else
{
fileWriter(1, address);
}
console.log('Has script: ' + isScript);
}
phantom.exit(0);
});
page.onResourceRequested = function (req) {
try {
var link = document.createElement('a');
link.setAttribute('href', req.url); //extract asset's domain from URL
if (link.hostname == 'my.domain.net') {
isScript = true;
}
} catch(e) {
console.log("PAGE OPEN ERROR: " + e);
}
};
}
function fileWriter(type, line){
try {
fs.write("scriptlog.csv", type + ',' + line + ',' + Date.now() + ',' + system.args[2] + '\n', 'a');
} catch(e) {
console.log("FILE ERROR: " + e);
}
}
I am trying to download a PDF in my phonegap application and then immediately open it, but I get a File not Found error. It seems to download. Here is my code:
// Download
var url = "https://example/example.pdf";
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/';
var fileName = 'example.pdf';
fileTransfer.download(
uri,
fileURL,
function (entry) {
alert("download complete: " + entry.fullPath);
// Open
cordova.plugins.fileOpener2.open(
fileURL + fileName,
'application/pdf',
{
error: function (errorObj) {
alert('Error status: ' + errorObj.status + ' - Error message: ' + errorObj.message + ' ' + errorObj.fileURL);
},
success: function () {
alert('file opened successfully');
}
}
);
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
}
);
alert('Downloading...');
I'm also wondering where is the best place to save files like this, that should be available after the app is closed?
second argument to fileTransfer.download is the location on device where you want to download pdf file.
You are setting var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/'; Which I believe does not exist. You can use file system plugin to first get file location on your device and then save it on device. you can use below code snapet.
var url = "https://example/example.pdf";
var uri = encodeURI(url);
//var fileURL = 'cdvfile://localhost/persistent/com.mycompany.myApp/';
// var fileName = 'example.pdf';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
fileSystem.root.getDirectory("Dir_NAME", {
create: true,
exclusive: false
}, gotDirectory, fail);
}
function gotDirectory(entry) {
entry.getFile('yourFileNAme', {
create: true,
exclusive: false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
filePath = fileEntry.fullPath;
var fileTransfer = new FileTransfer();
fileTransfer.download(
'uri', filePath, function(entry) {
console.log("success");
//perform you launch task
}, function(error) {
console.log("error");
}, true, {});
}
I hope it will help you.
Even I am new to android but what I think that there is problem in URI
To open up a Uri in android it should have a structure like
file:///storage/....
(there should be 3 backslashes )
You can get more details here
The best place to save a pdf can be your sdcard or internal storage. Then the pdf will be available in your device even after the application closes.
If you wish to have the same pdf file, available in different devices while testing your application in different device/ or even in emulator you can save it in the assert folder of your android project.
hope this helps
What is the best practice to securely upload an image to a php script based on my code below? I'm using the file transfer cordova plugin to upload the image to a php script.
Javascript (file transfer cordova plugin)
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.imageLink = "test";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://example.com/upload.php", win, fail, options);
alert("Post Uploading");
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
$.mobile.loading('hide');
navigator.notification.alert("An error has occurred: Code = " + error.code, null, 'Alert', 'OK');
}
PHP
<?php
if(isset($_POST['imageLink'])) {
$imageLink = $_POST['imageLink'];
print_r($_FILES);
$new_image_name = $imageLink.".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], “uploads/“.$new_image_name);
}
?>
Any suggestions?
Depends on what to protect from:
Virus/threat pose as image -> use antivirus scanning before upload/save
Somebody snooping the packet in transmit -> use https
Somebody not user try to upload -> your own access control list
Malicous code embedded in image -> again, threat scanner
Above list is just a start though. Security is a rabbit hole that goes down deeper than what we expect it to be.