Image upload on Phonegap / framework 7 app - image

I'm creating this app with Phonegap and Framework 7.
In one of my views, i wanted to have a image upload button and i implemented the following code:
<script>
function selectPhoto() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY, }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://pedrofidalgo.pt/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);
}
</script>
<button class="btngaleria" onclick="selectPhoto();" style="margin-top:3vh; background-color: #5f919d;"> Upload image </button>
I then have a php file on a web server with this code:
<?php
print_r($_FILES);
$new_image_name = $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "/uploads/sitios".$new_image_name);
?>
I tried building the APK and when i click the button it simply doesn't do anything. When i tried the app in the browser, the console says that the function i'm calling with the button (selectPhoto) is not defined.. can someone give some guidance please?

You have an error in your code
function fail(error)
{
alert("An error has occurred: Code = " = error.code);
should be
function fail(error)
{
alert("An error has occurred: Code = " + error.code);

Related

How to upload images of CK-Editor .net core mvc

Upload Images to server selected with CK-Editor
Action Method .Net Core MVC
<script src="~/ckeditor/ckeditor.js"></script>
<script>
CKEDITOR.replace('editor1', {
customConfig: '/js/CustomConfig.js'
});
CKEDITOR.editorConfig = function (config) {
config.removeDialogTabs = 'image:advanced;image:Link;link:advanced;link:upload';
config.filebrowserImageUploadUrl = '/Home/Uploads' //Action for Uploding image
};
</script>
Your upload function should like below. It works for me. And I recommend you also can refer CKEditor FileUpload Helper. It should also help you.
[HttpPost]
public ActionResult UploadImg(IFormFile upload)
{
if (upload.Length <= 0 ) return null;
// check the upload file is image
if (!System.Drawing.Image.FromStream(upload.OpenReadStream()))
{
dynamic error= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" pls upload img"\"}}");
return Json(error);
}
var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();
Image image = Image.FromStream(upload.OpenReadStream());
int width = image.Width;
int height = image.Height;
// limit image size
if ((width > 750) || (height > 500))
{
var error = "The file size is wrong. ";
dynamic msg= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + error + "\"}}");
return Json(msg);
}
// file size limit, 500k
if (upload.Length > 500 * 1024)
{
var error= "file is too large";
dynamic msg= JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + error+ "\"}}");
return Json(msg);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot/images/CKEditorImages",
fileName);
using (var stream = new FileStream(path, FileMode.Create))
{
upload.CopyTo(stream);
}
var url = $"{"/images/CKEditorImages/"}{fileName}";
var successMessage = "upload successfully";
dynamic success = JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}");
return Json(success);
}

nativescript-background-http issue

I tried implementing image upload page for my app, but unfortunately the request is not reaching the server. I double checked this using tcpdump on the server side. The code doesnt seem to process beyond session.uploadFile in sendImages function
Please let me know if there is any issue with the code
var imageSource = require("image-source");
var frameModule = require("ui/frame");
var Observable = require("data/observable").Observable;
var fromObject = require("data/observable").fromObject;
var ObservableArray = require("data/observable-array").ObservableArray;
var platformModule = require("platform");
var permissions = require("nativescript-permissions");
var imagepickerModule = require("nativescript-imagepicker");
var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");
var fs = require("file-system");
var page;
var imageName;
var counter = 0;
function pageLoaded(args) {
page = args.object;
}
function onSelectSingleTap(args) {
var context = imagepickerModule.create({
mode: "single"
});
if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
.then(function () {
console.log("Permissions granted!");
startSelection(context);
})
.catch(function () {
console.log("Uh oh, no permissions - plan B time!");
});
} else {
startSelection(context);
}
}
function sendImages(uri, fileUri) {
imageName = extractImageName(fileUri);
var request = {
url: "http://maskingIpForPost:8081/mobilepic/ctk/uploadpic",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"file-Name": imageName,
"uid": 30
},
description: "{ 'uploading': " + imageName + " }"
};
var task = session.uploadFile(fileUri, request);
task.on("progress", progress);
task.on("error", error);
task.on("complete", complete);
task.on("responded", responded);
function responded(e) {
console.log("eventName: " + e.eventName);
console.log("data: " + e.data);
}
function progress(e) {
console.log("currentBytes: " + e.currentBytes);
console.log("totalBytes: " + e.totalBytes);
console.log("eventName: " + e.eventName);
}
function error(e) {
console.log("eventName: " + e.eventName);
console.log("eventName: " + e.responseCode);
console.log("eventName: " + e.response);
}
function complete(e) {
console.log("eventName: " + e.eventName);
console.log("response: " + e.responseCode);
}
return task;
}
function startSelection(context) {
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected_item) {
var localPath = null;
if (platformModule.device.os === "Android") {
localPath = selected_item._android;
} else {
// selected_item.ios for iOS is PHAsset and not path - so we are creating own path
let folder = fs.knownFolders.documents();
let path = fs.path.join(folder.path, "Test" + counter + ".png");
//let saved = imagesource.saveToFile(path, "png");
localPath = path;
}
alert("final path " + localPath);
if (localPath) {
var task = sendImages("Image" + counter + ".png", localPath);
//mainViewModel.get("items").push(fromObject({ thumb: imagesource, uri: "Image" + counter + ".png", uploadTask: task }));
}
counter++;
});
}).catch(function (e) {
console.log(e.eventName);
});
}
function extractImageName(fileUri) {
var pattern = /[^/]*$/;
var imageName = fileUri.match(pattern);
return imageName;
}
exports.pageLoaded = pageLoaded;
exports.onSelectSingleTap = onSelectSingleTap;
On Further research found the following
net.gotev.uploadservice.UploadService is undefined in background-http.android.js. At this moment i am not sure what this means. Would appreciate if anyone has idea about this
You need to change the following line in your code.
var session = bghttpModule.session("image-upload");
It has to be file upload
var session = bghttpModule.session("file-upload");
Just tested your code by using Azure Blob Storage PUT url at my side and got the below response.
ActivityManager: START u0 {act=android.intent.action.OPEN_DOCUMENT typ=image/* cmp=com.android.documentsui/.DocumentsActivity (has extras)} from pid 2835
JS: currentBytes: 4096
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: eventName: responded
JS: data:
JS: eventName: complete
JS: response: 201
thanks for the quick response, i tried running it on a emulator and i faced the above mentioned issue, i tried the same by connecting a device and it worked just fine.

image upload to a .NET server

This is the code I'm using. How do I specify the .NET server address which should receive the image?
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
oData.append("CustomField", "extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "abcd", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
}
else
{
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
Create a generic handler. In ProcessRequest event, put this base code
public void ProcessRequest(HttpContext context)
{
HttpPostedFile doc = context.Request.Files[0];
//Your code....
doc.SaveAs("YOUR_PATH" + "/" + doc.FileName);
}
The ajax post should go to this resource...

Phonegap camera.getPicture() missing file extension and header data

I've been struggling on this for a while.
When I upload an image in a phonegap application with camera.getPicture() and ft.upload() the image is uploaded without file extension. I read it was because of a cache thing, providing a link to the actual file entry or something.
It was annoying me but I moved on since the image was uploaded fine on my server and displayed fine too even without file extension.
But today, we figured images were sometime rotated by 90°.
I instantly made the connection between the missing part of the image data and this issue, and I guess (not sure) I am right on this point.
I read image rotated by 90° could be caused by missing header meta data, so I guess not only the file extension were missing after all..
Could someone explain me what am I missing in the code and what to do or in which direction to look ? That would be awesome.
Here is part of my code (I can give you more if needed)
navigator.camera.getPicture(function(uri) {
try {
var imageURI = uri;
...
var ft = new FileTransfer();
ft.upload(imageURI, "some_script.php", function(r) {
...
Note:The image stored in database seems fine, the issue happens when the image is displayed in an tag.
Here an example of file getting rotate once uploaded (I added manually the .jpg extension so I could upload it on noelshack otherwise not able to). As you can see, the link to image is OK but once in tag it gets rotated
http://image.noelshack.com/fichiers/2015/41/1444168922-35-1444166605.jpg
http://jsfiddle.net/c3ybkqt8/
tl;dr
How to upload an image file entirely with phonegap including file extension & metadata header and not only a sort of cached file entry.
iOS Code
function capturePhoto() {
navigator.camera.getPicture(uploadPhoto, onFail, {
quality: 50,
// allowEdit: true,
correctOrientation: true,
destinationType: Camera.DestinationType.FILE_URL,
// destinationType: Camera.DestinationType.DATA_URL
sourceType: Camera.PictureSourceType.CAMERA
}
);
}
// function onPhotoDataSuccess(imageData) {
// localStorage.setItem("ImageData",imageData);
// localStorage.setItem("captureImgFlag",captureImgFlag);
// window.location = 'profileUserImgUploadInGallary.html';
// }
function onFail(message) {
// alert('Failed because: ' + message);
}
function uploadPhoto(imageURI){
console.log(imageURI);
spinnerplugin.show();
var UserId = localStorage.getItem('UserId');
// imgPostGallary
// var img = document.getElementById('imgPostGallary');
// var imageURI = img.src;
// var imageURI = imageData;
// img.src = imageURI;
// var ImageDataUp = localStorage.getItem('ImageDataUp');
// var imageURI = ImageDataUp;
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://XYZ/uploadimg?user_id="+UserId+""), winGallary, fail, options);
console.log(ft.upload);
}
function winGallary(rGallary) {
console.log("Code = " + rGallary.responseCode);
console.log("Response = " + rGallary.response);
console.log("Sent = " + rGallary.bytesSent);
spinnerplugin.hide();
window.location = 'profileUserImgUploadInGallary.html';
}
function fail(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
Hello, here is full example it's working for me capturing photos and set in image tag and upload that photos on server. and still you have facing any problem message me.
<img id="profileImageId">
<script type="text/javascript">
var profileImage = '';
function profileCapturePhotoEdit() {
navigator.camera.getPicture(profileonPhotoDataSuccess, onFail, {
quality: 50,
// allowEdit: true,
correctOrientation: true, // using this your image not roted 90 degree
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA }
);
}
function profileonPhotoDataSuccess(imageData) {
localStorage.setItem("imageDataProfile","data:image/jpeg;base64," + imageData);
var imageDataProfile = localStorage.getItem("imageDataProfile");
document.getElementById('profileImageId').src = imageDataProfile;
}
function onFail(message) {
// alert('Failed because: ' + message);
}
</script>
<!-- uploadProfileImage -->
<button onclick="uploadProfileImage();">
Upload Profile Image
</button>
<script type="text/javascript">
function uploadProfileImage() {
var UserId = localStorage.getItem('UserId');
var img = document.getElementById('profileImageId');
var imageURI = img.src;
var options = new FileUploadOptions();
options.fileKey="file"; // your file key in your .php file change here
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg"; // your extension
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://XYZ?user_id="+UserId+""), winProfile, failProfile, options);
}
function winProfile(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
// alert('Send success');
}
function failProfile(error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>

NativeScript HTTP:getJSON doesn't work

I have used the original helloworld app and just change the model from HelloWorldModel to MainModel.
Then i required "http" but when i run the app and klik the button for "updateAction" it only writes to the console and sets the message.
The HTTP request doesn't do anything.
Code: (main-view-model.js)
var __extends = this.__extends || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
__.prototype = b.prototype;
d.prototype = new __();
};
var observable = require("data/observable");
var http = require("http");
var MainModel = (function(_super) {
__extends(MainModel, _super);
function MainModel() {
_super.call(this);
console.log("MainModel called");
this.set("message", "Last updated" + " 2015-07-22 00:00:00");
this.set("message2", "Last updated" + " 2015-07-22 00:00:00");
}
MainModel.prototype.updateAction = function() {
console.log("updateAction");
this.set("message2", "Last updated" + " 2015-07-22 01:00:00");
http.getJSON("https://httpbin.org/get").then(function(r) {
this.set("message", "Last updated \n" + r);
console.log("SUCCESS");
console.log(r);
}, function(e) {
// Argument (e) is Error!
console.log("FAIL");
console.log(e);
this.set("message", "Last updated \n" + e);
});
};
return MainModel;
})(observable.Observable);
exports.MainModel = MainModel;
exports.mainViewModel = new MainModel();
What am I doing wrong?
Note: I'm testing on iPhone 6 emulator
It seems that using getString works and gives the same response.
Still wierd the getJSON doesn't work.
A working example is:
http.getString("https://httpbin.org/get").then(function (r) {
console.log("SUCCESS");
console.log(r);
}, function (e) {
console.log("FAIL");
console.log(e);
});

Resources