I am developping a Nativscript-Vue mobile app, and I need to be able to select a file from the image gallery and upload it to an online file manager (I use 000webhost.com).
I worked with a code sample I got from the NativeScript website, and I am able to get the picture without problems, but I can't manage to upload it to WebHost (the logs says that the upload is successful, and there's no error showing up, but my pictures folder remains empty for some reason).
Here's my code :
<template>
<Page class="page">
<ActionBar title="imagepicker + background-http" class="action-bar"></ActionBar>
<GridLayout rows="*, auto">
<GridLayout v-if="!showWelcome" rows="auto auto auto, *">
<Progress :value="event && event.eventData ? event.eventData.currentBytes : 0"
:maxValue="event && event.eventData ? event.eventData.totalBytes : 0">
</Progress>
<Label row="1" v-if="event && event.eventData && event.eventData.currentBytes !== NaN"
class="m-10 text" :text="'Transferred: ' + event.eventData.currentBytes / 1000 + ' KB'"></Label>
<Label row="2" class="m-10 text" text="Events"></Label>
<ListView row="3" for="item in eventLog">
<v-template>
<StackLayout class="t-12">
<Label :text="item.eventTitle" textWrap="true"></Label>
<Label v-if="item.eventData && item.eventData.error"
:text="item.eventData ? 'Error: ' + item.eventData.error : ''"
textWrap="true"></Label>
<Label v-if="item.eventData && item.eventData.body"
:text="item.eventData ? 'Body: ' + item.eventData.body : ''"
textWrap="true"></Label>
<Label v-if="item.eventData && item.eventData.raw"
:text="item.eventData ? 'Raw: ' + item.eventData.raw : ''"
textWrap="true"></Label>
</StackLayout>
</v-template>
</ListView>
</GridLayout>
<StackLayout v-if="showWelcome" verticalAlignment="middle">
<Label class="m-10 nativescript-label text" text="{N}"></Label>
<Label class="m-10 text" v-if="showWelcome" text="This sample app shows how to pick an image with"
textWrap="true"></Label>
<Label class="m-10 text plugin" text="nativescript-imagepicker"></Label>
<Label class="m-10 text" v-if="showWelcome" text="and upload it using"
textWrap="true"></Label>
<Label class="m-10 text plugin" text="nativescript-background-http"></Label>
</StackLayout>
<Button class="m-b-10 m-t-10 t-20" row="1" text="Choose image to upload" #tap="onSelectImageTap($event)"></Button>
</GridLayout>
</Page>
</template>
<script>
import VueRx from "../vue-rx";
import Vue from "nativescript-vue";
const app = require("tns-core-modules/application");
const platform = require("platform");
const fs = require("file-system");
const imagePicker = require("nativescript-imagepicker");
const rxjs = require("rxjs");
const operators = require("rxjs/operators");
const bgHttp = require("nativescript-background-http");
Vue.use(VueRx);
// Vue.config.silent = false; // uncomment for debugging purposes
export default {
data() {
return {
showWelcome: true,
session: bgHttp.session("image-upload"),
currentFileNameBeingUploaded: ""
};
},
subscriptions() {
this.event$ = new rxjs.BehaviorSubject({});
return {
event: this.event$,
eventLog: this.event$.pipe(
operators.sampleTime(200),
operators.concatMap(value => rxjs.of(value)),
operators.scan((acc, logEntry) => {
acc.push(logEntry);
return acc;
}, []),
// emit only logs for the this.currentFileNameBeingUploaded
operators.map(allLogs => allLogs.filter(logEntry => !!logEntry && logEntry.eventTitle && logEntry.eventTitle.indexOf(this.currentFileNameBeingUploaded) > 0))
)
};
},
methods: {
onSelectImageTap() {
let context = imagePicker.create({
mode: "single"
});
this.startSelection(context);
},
startSelection(context) {
context
.authorize()
.then(() => {
return context.present();
})
.then(selection => {
this.showWelcome = false;
let imageAsset = selection.length > 0 ? selection[
0] : null;
if (imageAsset) {
this.getImageFilePath(imageAsset).then(path => {
console.log(`path: ${path}`);
this.uploadImage(path);
});
}
})
.catch(function(e) {
console.log(e);
});
},
uploadImage(path) {
let file = fs.File.fromPath(path);
this.currentFileNameBeingUploaded = file.path.substr(
file.path.lastIndexOf("/") + 1
);
let request = this.createNewRequest();
request.description = "uploading image " + file.path;
request.headers["File-Name"] = this.currentFileNameBeingUploaded;
// -----> multipart upload
// var params = [{
// name: "test",
// value: "value"
// },
// {
// name: "fileToUpload",
// filename: file.path,
// mimeType: "image/jpeg"
// }
// ];
// var task = this.session.multipartUpload(params, request);
// <----- multipart upload
let task = this.session.uploadFile(file.path, request);
task.on("progress", this.onEvent.bind(this));
task.on("error", this.onEvent.bind(this));
task.on("responded", this.onEvent.bind(this));
task.on("complete", this.onEvent.bind(this));
},
createNewRequest() {
let url;
// NOTE: using https://httpbin.org/post for testing purposes,
// you'll need to use your own service in real-world app
if (platform.isIOS) {
url = "https://ipaccovoiturage.000webhostapp.com/pictures";
} else {
url = "https://ipaccovoiturage.000webhostapp.com/pictures";
}
let request = {
url: url,
method: "POST",
headers: {
"Content-Type": "application/octet-stream"
},
description: "uploading file...",
androidAutoDeleteAfterUpload: false,
androidNotificationTitle: "NativeScript HTTP background"
};
return request;
},
getImageFilePath(imageAsset) {
return new Promise(resolve => {
if (platform.isIOS) {
const options = PHImageRequestOptions.new();
options.synchronous = true;
options.version =
PHImageRequestOptionsVersion.Current;
options.deliveryMode =
PHImageRequestOptionsDeliveryMode.HighQualityFormat;
PHImageManager.defaultManager().requestImageDataForAssetOptionsResultHandler(
imageAsset.ios,
options,
nsData => {
// create file from image asset and return its path
const tempFolderPath = fs.knownFolders
.temp()
.getFolder("nsimagepicker").path;
const tempFilePath = fs.path.join(
tempFolderPath,
Date.now() + ".jpg"
);
nsData.writeToFileAtomically(
tempFilePath, true);
resolve(tempFilePath);
}
);
} else {
// return imageAsset.android, since it 's the path of the file
resolve(imageAsset.android);
}
});
},
onEvent(e) {
let eventEntry = {
eventTitle: e.eventName + " " + e.object.description,
eventData: {
error: e.error ? e.error.toString() : e.error,
currentBytes: e.currentBytes,
totalBytes: e.totalBytes,
body: e.data
// raw: JSON.stringify(e) // uncomment for debugging purposes
}
};
this.event$.next(eventEntry);
}
}
};
</script>
<style scoped>
.home-panel {
vertical-align: center;
font-size: 20;
margin: 15;
}
.description-label {
margin-bottom: 15;
}
.text {
text-align:
center;
font-size: 18px;
}
.plugin {
font-weight: 600;
font-size: 23px;
}
.nativescript-label {
font-size: 60px;
background-color: #3d5afe;
font-weight: 600;
color: white;
border-radius: 20px/20px;
width: 230px;
height: 230px;
}
</style>
I thought maybe WebHost was the problem, but I've been able to insert photos with PHP and HTML (unfortunately NativeScript-Vue doesn't allow HTML).
I had a similar issue in plain javascript. I was working on it for a couple of days. #Manoj answers didn't work for me. I had to use multipartUpload since I am sending an additional parameter.
Make sure to match the name parameter (fileToUpload) in the request to the name expected by your service. "file" in my case.
The service API signature looks like:
public async Task<IActionResult> Upload(string listingId, IFormFile file)
My request:
const request = {
url: "yoururl",
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
"Authorization": token
},
description: `Uploading image ${name}`,
androidAutoDeleteAfterUpload: true,
androidNotificationTitle: "HTTP background"
};
const params = [
{
name: "listingId",
value: 2
},
{
name: "file", // Note it is not fileToUpload but file instead.
filename: path,
mimeType: "image/jpeg"
}
];
const task = session.multipartUpload(params, request);
I hope it helps. By the way both Content-Type multipart/form-data and application/octet-stream work for me, but I use multipart/form-data for consistency
I am trying to convert an #Html.Textbox image button to submit button with the onclick calling a Javascript function but I can't seem to figure out the validation part. I believe it does need to be a submit button.
I am basically trying to get rid of the image but keep the functionality.
Here's what's working today.
#Html.TextBox("Next", null, new {type = "image", src = #Url.Content("../App_Themes/icons/button_next.png"), #class = "imgbottom", onclick = "javascript: ValidateSelection ($(\"[name$='selectedItems']:checked\"))"})
function ValidateSelection(item) {
if (item == null || item.length == 0) {
var validationSummary = $('.validation-summary-errors ul');
if (validationSummary.length > 0 && $('.validation-summary-errors ul li').length == 0) {
validationSummary.append('<li>' + "Please select at least one item" + '</li>');
}
var errors = $("[name='ErrorMessage']");
if (errors.length > 0) {
errors.hide();
}
var buttonGenerateReport = $("#GenerateReport");
if (buttonGenerateReport.length > 0) {
buttonGenerateReport.hide();
}
event.preventDefault();
}
}
<button type="submit" class="imgbottom" onclick="ValidateSelection('selectedItems');">
<img src="#Url.Content("~/App_Themes/icons/button_next.png")" alt="Next" /><br />
Next
</button>
The "~/" part of the Url Content string represents your project root, so adjust it to fit your correct file address later.
Or you could just use FontAwesome and replace your image entirely by that. It's size scalable because of CSS and has a simpler syntax.
<button type="submit" class="imgbottom" onclick="ValidateSelection('selectedItems');">
<i class="fa fa-angle-double-right" aria-hidden="true"></i> Next
</button>
Then in your jQuery function:
function ValidateSelection(elementName){
var selectedItems = $("[name='" + elementName + "']:checked");
if (selectedItems === null || selectedItems.length === 0) {
var validationSummary = $('.validation-summary-errors ul');
if (validationSummary.length > 0 && $('.validation-summary-errors ul li').length == 0) {
validationSummary.append('<li>' + "Please select at least one item" + '</li>');
}
var errors = $("[name='ErrorMessage']");
if (errors.length > 0) {
errors.hide();
}
var buttonGenerateReport = $("#GenerateReport");
if (buttonGenerateReport.length > 0) {
buttonGenerateReport.hide();
}
event.preventDefault();
}
}
How to upload multiple images in code ignite r. Please any body shear code .
this is my code to upload a file which is written in a controller.Please any body suggest what is wrong with this code.
function do_upload_slider()
{
$this->load->library('upload');
$files = $_FILES;
echo $cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload_slider();
}
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './uploads/slider/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['overwrite'] = TRUE;
return $config;
}
try this one.it may be help you
uploadform_view.php.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('imageupload/doupload');?>
<input name="userfile[]" id="userfile" type="file" multiple="" />
<input type="submit" value="upload" />
<?php echo form_close() ?>
</body>
</html>
Create A New Controller: controllers/imageupload.php
class Imageupload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('imageupload_view', array('error' => ' ' ));
}
function doupload() {
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
}
}
And that is it. Customize it to your needs, the basics are there already. And good luck!
In my MVC application am allowing the user to upload a file. Whenever user clicks on upload file link this is the link
<a class="upload" onclick="upload(this);">
the file upload should get open in modal box.
function upload(box) {
var box = dhtmlx.modalbox({
title: "Upload File",
text: "<div id='form_in_box'><div>Choose a PDF file to upload <hr/><label>Enter the URL <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Upload File' style='width: 86px' onclick='save_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
function close_file(box) {
dhtmlx.modalbox.hide(box);
}
function save_file(box) {
var file = $("#file").val();
if (file == "") {
alert("Enter the URL");
return false;
dhtmlx.modalbox.hide(box);
dhtmlx.message("Uploading the file");
$.post("/FileUpload/Upload",
{ file: '' + file + '' });
}
and the controller code is
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
SaveFile(file);
return RedirectToAction("Index");
}
but the problem is am getting error i.e. file = null
You cannot upload files using an AJAX request ($.post). If your browser supports the HTML5 File API you could use the new XHR2 object. If not, you could use a file upload plugin such as Uploadify, Fine Uploader or PLUpload. All those plugins will detect whether the client browser supports the HTML5 File API and use it if so and if it doesn't they will fallback to standard techniques such as using hidden iframes or Flash movies. The advantage of using one of them is that you don't need to be coding for all the possible cases.
Here's an example of how you could upload the file using the HTML5 File API:
function save_file(box) {
var file = document.getElementById('file');
if (file.value == '') {
alert('Enter the URL');
return false;
}
dhtmlx.modalbox.hide(box);
dhtmlx.message('Uploading the file');
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Upload', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('file successfully uploaded to the server');
}
};
xhr.send(fd);
}
Can some tell me how to make this script check for the password before it starts the upload process instead of after the file is uploaded? Some of the files I need uploaded are big and it sucks to wait till the file is uploaded to before it tells me that the password was wrong.
Thanks for any help you can provide.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>ES Simple Uploader</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="generator" content="handmade" />
<style type="text/css">
<!--
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
background-color: #DDDDDD;
}
.cnt {
text-align: center;
}
.cnt_welcome {
font-size: 16px;
font-weight: bold;
text-align: center;
}
.cnt_powered {
font-size: 14px;
font-weight: bold;
text-align: center;
}
.cnt_small {
font-size: 12px;
text-align: center;
padding-top: 50px;
}
.head_line {
background-color: #BBBBBB;
}
.main_table {
border: solid 1px #9D9992;
font-size: 13px;
}
h4 {
font-size: 12px;
color: #DD0000;
text-align: center;
}
.button {
border: 1px solid #55555;
font-weight: bold;
}
-->
</style>
</head>
<body>
<?
include("config.php");
function path_options()
{
global $upload_dirs;
$option = "";
foreach ($upload_dirs as $path => $pinfo)
{
$option .= '<option value="'.$path.'">'.$pinfo["name"].'</option>';
}
return $option;
}
function check_vals()
{
global $upload_dirs, $err;
if (!ini_get("file_uploads")) { $err .= "HTTP file uploading is blocked in php configuration file (php.ini). Please, contact to server administrator."; return 0; }
$pos = strpos(ini_get("disable_functions"), "move_uploaded_file");
if ($pos !== false) { $err .= "PHP function move_uploaded_file is blocked in php configuration file (php.ini). Please, contact to server administrator."; return 0; }
if (!isset($_POST["path"]) || (strlen($_POST["path"]) == 0)) { $err .= "Please fill out path"; return 0; }
if (!isset($upload_dirs[$_POST["path"]])) { $err .= "Incorrect path"; return 0; }
if (!isset($_POST["pwd"]) || (strlen($_POST["pwd"]) == 0)) { $err .= "Please fill out password"; return 0; }
elseif ($_POST["pwd"] != $upload_dirs[$_POST["path"]]["password"]) { $err .= "The upload password is incorrect"; return 0; }
if (!isset($_FILES["userfile"])) { $err .= "Empty file"; return 0; }
elseif (!is_uploaded_file($_FILES['userfile']['tmp_name'])) { $err .= "Empty file"; return 0; }
return 1;
}
$err = ""; $status = 0;
if (isset($_POST["upload"])) {
if (check_vals()) {
if (filesize($_FILES["userfile"]["tmp_name"]) > $max_file_size) $err .= "Maximum file size limit: $max_file_size bytes";
else {
if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $upload_dirs[$_POST["path"]]["dir"].$_FILES["userfile"]["name"])) {
$status = 1;
}
else $err .= "There are some errors!";
}
}
}
if (!$status) {
if (strlen($err) > 0) echo "<h4>$err</h4>";
}
else {
echo "<h4>"".$_FILES["userfile"]["name"]."" was successfully uploaded.</h4>";
}
?>
<p class="cnt_welcome">Welcome to ES Simple Uploader v 1.1.</p>
<p class="cnt">« Back to Product page «</p>
<p class="cnt">(Select folder, set it's password, then select a file to upload and click "Upload" button).
<br />Note:
Folder: "Images folder", Password: "images";
Folder: "Docs", Password: "docs";
Folder: "Common files", Password: "common";
Maximum file size: <?=$max_file_size/1024?> Kb.</p><br />
<form enctype="multipart/form-data" action="index.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
<table class="main_table" align="center">
<tr>
<td colspan="2" class="head_line"> </td>
</tr>
<tr>
<td>Folder:</td>
<td><select name="path"><?=path_options()?></select></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd" style="width: 217px;" /></td>
</tr>
<tr>
<td>Choose file:</td>
<td><input type="file" name="userfile" style="width: 222px;" /></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" name="upload" value="Upload" class="button" /></td>
</tr>
</table>
</form>
</p>
<p class="cnt_powered">Powered by EnergyScripts</p>
<p class="cnt_small">Find more power solution: ES File Upload & Download Manager</p>
</body>
</html>