I use image picker to get photo from camera then upload it to the server with base64Encode, like this
http.post( api('file/update_pic_item/2'), body: data, headers: {HttpHeaders.authorizationHeader: prefs.getString('token'), "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"}).then((response) async {
toast('Success');
Map res = json.decode(response.body); print(res);
});
By server I got this message
The pic1 must be an image., The pic1 must be a file of type: jpeg, jpg, bmp, png
I use lumen for my backend,
$this->validate($request, [
'pic1' => 'nullable|image|mimes:jpeg,jpg,bmp,png|max:10240', ]);
$upload_path = 'images/items';
if ($request->hasFile('pic1')) {
$pic1 = $request->file('pic1');
$ext1 = $pic1->getClientOriginalExtension();
if ($pic1->isValid()) {
$pic_name = Carbon::now()->format('YmdHs') . "a." . $ext1;
$pic1->move($upload_path, $pic_name);
$item->update(['pic1' => $pic_name]);
}
}
How to solve this problem? thank you so much for your help
Use this code to upload image on server
Future upload(File imageFile)async{
var stream= new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length= await imageFile.length();
var uri = Uri.parse('imageUrl');
var request = new http.MultipartRequest("POST", uri);
var imageUri = 'salati_${widget.user.user_id}_${DateTime.now().millisecondsSinceEpoch}'+imageFile.path.substring(imageFile.path.lastIndexOf("."));
var multipartFile = new http.MultipartFile("image", stream, length, filename: basename(imageUri));
request.files.add(multipartFile);
var response = await request.send();
if(response.statusCode==200){
print("Image Uploaded");
}else{
print("Upload Failed");
}
}
Searched through the Overflow to see if I can spot a solution to this issue, but unfortunately nothing seems to be specific enough.
I'm building an Ionic app with a photo upload feature (using the cordova-filetransfer plugin), and have an API endpoint set up to receive the image. The Ionic JS is able to process the image successfully, but the API responds back with the "disallowed keys" error; only it's full of random garbled nonsense.
The clean_input function:
public function clean_input_keys($str)
{
$chars = PCRE_UNICODE_PROPERTIES ? '\pL' : 'a-zA-Z';
if ( ! preg_match('#^['.$chars.'0-9:_.-]++$#uD', $str))
{
exit('Disallowed key characters in global data: '.$str."\n [GLOBAL vars] \n".Kohana::debug($GLOBALS));
}
return $str;
}
The full response:
Disallowed key characters in global data: '()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÛ
[GLOBAL vars]
<pre>array: </pre>
The uploadImage function from the mobile app:
$scope.uploadImage = function(datetime) {
// Destination URL
var uploadUrl = "url/goes/here";
// File for Upload
var imagePath = $scope.urlForImage($scope.image);
console.log('Path: '+imagePath);
// File name only
var filename = $scope.addZero(datetime.getDate()) + $scope.addZero((datetime.getMonth() + 1)) + datetime.getFullYear() + '-' + $scope.addZero(datetime.getHours()) + $scope.addZero(datetime.getMinutes()) + '-' + $scope.incidentData.store + '-' + $scope.incidentData.location + '.jpg';
filename = filename.replace(/\s+/g, '');
console.log('Filename: '+filename);
var success = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
};
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("Upload error source " + error.source);
console.log("Upload error target " + error.target);
};
var options = new FileUploadOptions();
options.fileKey = "image";
options.fileName = filename;
options.chunkedMode = false
//mimeType: "multipart/form-data",
options.mimeType = "image/jpeg";
var params = {};
params.fileName = filename;
options.params = params;
var headers = {
"API-Key": "keygoeshere",
"Content-Type": "application/x-www-form-urlencoded"
};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(imagePath, uploadUrl, success, fail, options);
}
And the API endpoint function:
public function upload_image()
{
$this->authorise();
$file_temp = $_FILES['image']['tmp_name'];
$file_name = $_FILES['image']['name'];
$target_path = 'path/goes/here';
if (move_uploaded_file($file_temp, $target_path.$file_name)) {
Kohana::log('debug', 'File received: '.$_FILES['image']['name']);
Kohana::log_save();
} else {
Kohana::log('debug', 'Photo upload failed');
Kohana::log_save();
}
}
Sorry if this is a bit too much code, but I cannot work out for the life of me where this error is stemming from - any advice?
The issue turned out to be the headers: I was posting a header (Content-Type) that the plugin already sends by default; the two were clashing and causing the error.
Removing this header, leaving only the API-Key, has allowed the image to be sent.
I've made a script which uses $.ajax and FormData to pass two form objects to PHP. One form object is a text and the other is a file.
It worked well as a stand-alone script. However, after I added it to Wordpress, as a plugin, it keeps giving me "Uncaught TypeError: Illegal invocation".
I can't afford to serialize the formdata, simply because then I won't be able to pass the file to the callback function in PHP.
JS involving FormData before ajax call:
var fd = new FormData();
var file = jQuery(this).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
This part above is 100% correct.
Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
This is incredibly frustrating since it worked perfectly fine outside of Wordpress. I've tried de-registering Wordpress' jQuery and enqueueing the latest jQuery version, but it made no difference.
To recap:
1) Ajax/jQuery is refusing to pass a form object to PHP
2) Can't serialize the object because I need to preserve the file object
3) Script works outside of Wordpress
4) Tried updating to the newest jQuery version, no change
try this :
jQuery(document).on('click', '#submit', function(e){
e.preventDefault();
var fd = new FormData();
var file = jQuery(document).find('input[type="file"]');
var caption = jQuery(this).find('input[name=img_caption]');
var individual_file = file[0].files[0];
fd.append("file", individual_file);
var individual_capt = caption.val();
fd.append("caption", individual_capt);
fd.append('action', 'fiu_upload_file');
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: fd,
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
php
function fiu_upload_file(){
var_dump($_FILES);
exit();
}
add_action('wp_ajax_fiu_upload_file', 'fiu_upload_file');
add_action('wp_ajax_nopriv_fiu_upload_file', 'fiu_upload_file');
I managed to do it. The code works on the latest version of Wordpress (4.9.4)
First of all, I'm using XMLHttpRequest to send the data and not the jQuery ajax. This means that you can adapt it to just pure JS.
Notice the xhttp.setRequestHeader("enctype","multipart/form-data"); which was essential to pass the FormData using this method.
JS:
var user_id = $('#user_id').val();
var picture = $('#userPic')[0].files[0];
console.log(picture);
if( picture && typeof picture !== undefined ) {
if ( picture['size'] > 1000000 ) {
alert('The Profile Pic can\'t be larger than 1Mb.');
return;
}
if ( picture['type'].indexOf('image') == -1 ) {
alert('The uploaded file needs to be an image.');
return;
}
var data = new FormData();
data.append('user_id', user_id);
data.append('userPic', picture);
// console.log(data);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('Receive:' + this.responseText);
}
};
xhttp.open("POST", location.origin + "/wp-content/themes/search-and-go-child/ajax/upload_user_profile_pic_ajax.php", true);
xhttp.setRequestHeader("enctype","multipart/form-data");
xhttp.send(data);
}
The PHP part is also extremely useful since it requires the files needed to manipulate the received data with the WP core functions.
Here you will also find the code to upload an attachment using the WP core functions.
PHP:
// error_reporting(-1);
// ini_set('display_errors', 'On');
$path = $_SERVER['DOCUMENT_ROOT'];
require_once($path.'/wp-load.php');
require_once( '/home/s24t06b21lk5/public_html/wp-includes/template-loader.php' );
// require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/image.php');
require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/file.php');
// require_once("/home/s24t06b21lk5/public_html/wp-admin" . '/includes/media.php');
$user_id = $_POST['user_id'];
$picture = $_FILES['userPic'];
var_dump($user_id);
var_dump($picture);
$response = array();
if( isset($picture['name']) && $picture['name'] ) {
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
$picture['name'] = preg_replace( '/[^0-9a-zA-Z.]/', '', basename( $picture['name'] ) );
// Upload the file
$upload_overrides = array( 'test_form' => false );
$upload_result = wp_handle_upload($picture, $upload_overrides);
// echo '<pre>'; print_r($upload_result); echo '</pre>' ;
if( $upload_result['url'] ) {
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $upload_result['url'],
'post_mime_type' => $picture['type'],
'post_title' => $picture['name'],
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload_result['file'] );
if( $attach_id ) {
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_result['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
// Update the usermeta table with the uploaded avatar
if( !update_user_meta($user_id, 'wp_user_avatar', $attach_id ) || !update_user_meta($user_id, 'wp_zfgrf5v7rw_user_avatar', $attach_id) ) {
$response['result'] = FALSE;
$response['message'] = "The uploaded image could not be associated with the User ID in the database.";
}
else {
$response['result'] = TRUE;
}
}
else {
$response['result'] = FALSE;
$response['message'] = "Wordpress attachment post for the user's image could not created.";
}
}
else {
$response['result'] = FALSE;
$response['message'] = "The file couldn't be uploaded. Check the permissions.";
}
}
die( json_encode($response) );
Thank you.
Works whith any input(one or many simple or multiple), textarea, select in your form (WP 5.0.3)
$('#form').submit(function(e) {
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
formdata.append("action", "fiu_upload_file");
$.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(data){
if(data.error == 'true') {
$('.msg').html(data.true);
}
else {
$('.msg').html(data.false);
// your code if you want an action ...
};
}
});
});
and php for only the files
foreach ($_FILES as $file) :
if($file['error'] == UPLOAD_ERR_NO_FILE) :
continue;
endif;
$valid_ext = array( 'jpg' , 'jpeg' , 'png' , 'doc' , 'docx' , 'pdf' , 'xls' , 'xlsx');
$extension_upload = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ( in_array($extension_upload,$valid_ext) ) :
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$msg_true = 'Upload ok ';
else :
$msg_error = 'Upload error';
endif;
endforeach;
$result = !isset($msg_error);
$msg = array();
if($result) :
$msg['error'] = 'true';
$msg['true'] = $msg_true;
else :
$msg['error'] = 'false';
$msg['false'] = $msg_error;
endif;
header('Content-Type: application/json');
echo json_encode($msg);
I added
dataType: 'json'
and it helps.
Full listing of your code of Ajax call:
jQuery.ajax({
type: 'POST',
url: fiuajax.ajaxurl,
data: {
action: 'fiu_upload_file',
security: fiuajax.security,
data: fd,
dataType: 'json',
contentType: false,
processData: false,
},
success: function(response){
var dataObj = jQuery.parseJSON(response);
if(dataObj.message == 'error') {
jQuery('.fiu_validation').html('The following error occured: '+dataObj.desc);
}
else if(dataObj.message == 'success') {
jQuery('.fiu_file').val('');
}
console.log(response);
}
});
here some modified code in case you have multiple data and multiple files
var fd = new FormData();
var data = jQuery('#yourformID').serializeArray();
jQuery.each(data,function(key,input){
fd.append(input.name,input.value);
});
var file = jQuery(document).find('input[type="file"]');
jQuery.each(jQuery(file), function(i, obj) {
jQuery.each(obj.files,function(j,file){
fd.append('files[' + j + ']', file);
})
});
fd.append('action', 'fiu_upload_file');
I have a problem in uploading photo into server which is taken by camera.
I have tried to used the code in Mosync site but it doesn't work.
In the sample code below,
my app always return "Could not upload photo - error: 3"
app.uploadPhoto = function(fileURL)
{
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = app.getMimeType(options.fileName);
options.params = null;
var transfer = new FileTransfer();
transfer.upload(
fileURL,
"http://dev.mosync.com/mobilelua/PhotoGallery/upload.php",
function(result)
{
alert("Photo uploaded");
},
function(error)
{
alert("Could not upload photo - error: " + error.code);
},
options);
};
I am designing a app in phonegap. I send multiple base64 images to php webservice. Now i need to decode all those base64 images and save them into database.
I am hoping for the best solution. Thank you.
This is my code for assigning base64 values into a hidden input type.
for(i = 0; i< image.length;i++){
$('#table_postad').append('<input type="hidden" value="'+image[i]+'" name="ad_image'+i+'" class="ad_image"/>');
imageArray.push(document.getElementsByClassName("ad_image")[i].value);
}
Following is the code to connect server:
var server = 'http://example.com/webServiceForProject/';
function sendDataToServer(){
alert("access");
var datas = $("#form_description").serialize();//form_description is id for form
console.log(datas);
$.ajax({
type: 'POST',
data: datas,
url: server+'insert.php',
success: function(data){
alert(data);
},
error: function(){
alert('There was an error adding your comment');
}
});
}
this is php code:
<?php
define('UPLOAD_DIR', 'images/');
$adPhotos = array();
$i=0;
while(isset($_POST["ad_image".$i])){
array_push($adPhotos,($_POST["ad_image".$i]));
$i++;
echo($adPhotos[i]);
}
$j = 0;
while(sizeof($adPhotos)){
$adPhotos[$j]= str_replace('data:image/png;base64,', '', $adPhotos[$j]);
$adPhotos[$j]= str_replace(' ', '+', $adPhotos[$j]);
$file[$j] = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file[$j], $data[$j]);
j++;
}
//insert code here.....
?>
Use php's base64_decode to decode the image and save it to your database (e.g. with mysql_query and an INSERT INTO...-statement.
Ram, you don't have to convert images to base64. Please use this code.
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {}
function browseImage() {
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 80,
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;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://example.com/api/upload.php", win, fail, options);
}
function win(r) {
console.log("Response Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
console.log("Error: Code = " = error.code);
}
</script>
<input type="button" onclick= "browseImage()" value="Browse Image" />
//Server: PHP code to upload file
$img_name = $time."jpg";
if(move_uploaded_file($_FILES["file"]["tmp_name"], "folder/".$img_name)){ //upload files in location folder/
//use mysql query to save the filename. (mysql_query("insert into tbl_name(image) values('$img_name')"))
}