How do I send an image to a PHP API using VueJS? - php

I am trying to send an object which contains an image using Vue to a PHP API but honestly I don't know how,
I have my form
<form #submit='sendData'>
<div class="input-group">
<label for="name">Name</label>
<input type="text" #change="getText" name='text' id='text'>
</div>
<div class="input-group">
<label for="photo">Photo</label>
<input type="file" #change="getImage" name='photo' id='photo'>
</div>
</form>
export default{
data(){
return {
myData:{
text:'',
photo:''
}
}
}
and the getImage() like this
getImage(event){
let formData = new formData();
formData.append('photo',event.target.files[0]);
this.myData.photo=formData;
}
getText(event){
this.myData[event.target.name]=event.target.value;
}
sendData(event){
event.preventDefault();
this.$http.post('myapi/api/user',this.myData);
}
I don't know how to access this image in my PHP API and upload it to database.
I tried accessing $_FILES but it's an empty array
Sorry seems the problem is that I am sending some other data too and not only the formData

if you want to send an image to an api.
You form should specify the type de data you must send for
your form. you should add this.
<form enctype="multipart/form-data">
<input type="text" class="form-control" v-model="myData.text" />
<input type="file" class="form-control" #change="handleUpload($event.target.files)" />
</form>
In your script you need to set this methods
data () {
return {
myData: {
text: '',
photo: null
}
}
},
methods: {
handleUpload(files) {
this.myData.photo = files[0];
},
saveProductImage () {
let formData = new FormData()
formData.append('text', this.myData.text);
formData.append('photo', this.myData.photo);
// Send here
}
}
Please check the docs

Related

how to send addtional form data in froala editor through ajax request?

I am using froala editor v2, and I need to save the form content through ajax request, so I am tried following way
HTML
<form enctype="multipart/form-data" id="composeForm" action="#" method="post">
<input type="file" name="compose_attachments[]" id="file-7" class="inputfile theme-inputfile" accept=".jpg,.jpeg,.png,.xls,.xlsx,.csv,.pdf,.ppt,.doc,.docx" multiple />
<input type="text" class="form-control inputES" placeholder="Email Subject" name="compose_subject">
<input class="autoTags" type="text" value="" data-role="tagsinput" placeholder="" name="compose_to">
<input class="autoTags" type="text" value="" data-role="tagsinput" placeholder="" name="compose_cc">
<input class="autoTags" type="text" value="" data-role="tagsinput" placeholder="" name="compose_bcc">
<textarea class="froala-editor-mail" id="composeEmailBody" name="compose_body"></textarea>
<button type="button" class="btn btn-green-bs p-lr-30 mr-10" id="SendComposedEmail">SEND</button>
</form>
JS
<script>
var editor_compose = new FroalaEditor('#composeEmailBody', {
// Set the save URL.
saveURL: `${ajaxUrl}?method=sendTestEmail`,
// HTTP request type.
saveMethod: 'POST',
saveParams: new FormData($("#composeForm")[0]),
events: {
'save.before': function () {
// Before save request is made.
showLoader(0);
},
'save.after': function () {
// After successfully save request.
showLoader(1);
},
'save.error': function () {
// Do something here.
alert("Save error;");
}
}
});
document.querySelector('#SendComposedEmail').addEventListener("click", function () {
editor_compose.save.save();
});
</script>
PHP
<?PHP
case 'sendTestEmail':
echo "<pre>";print_r($_POST);print_r($_FILES);exit;
break;
?>
OUTPUT
Array
(
)
$_POST & $_FILES are empty and only got by editor HTML value.
so, I am not able to get formData in ajax request. how to resolve it??

Not able to fetch data in codeigniter from angular 4 view

I am using angular 4 for front end and CodeIgniter at the backend. At the angular end, there is a form that has some input values and images that I need to fetch at CodeIgniter end so that they can be saved in the database. But for an image, I wish to save it in a folder and then save its path in a database
Form code
<form ngNativeValidate [formGroup]="form" (ngSubmit)="onSubmitadd()" class="form-horizontal">
<input type="text" class="form-control" name="title" id="title" formControlName="title" minlength="10" maxlength="150" required>
<input type="file" id="avatar" (change)="onFileChange($event)" #fileInput required>
<button type="submit" class="demo-loading-btn btn red savebtn">Save</button>
</form>
onSubmitadd() {
const formModel = this.form.value;
this.loading = true;
this.http.post('http://www.localhost/litehires/company/profile',formModel ,{
})
.subscribe(
res => {
console.log(res);
$("#add-data .close").click();
this.listBanner();
},
err => {
console.log("Error occured");
}
);
}
Controller Code
public function profile()
{
$res = $this->input->post('formModel');
return $res;
}
While checking in a console the data is getting passed in formModel but I am not able to fetch the data in a controller. Can anyone please tell how to fetch the data and image so that I can process it further
You will have to use php input stream for this
$data = json_decode(file_get_contents('php://input'), true);
public function profile()
{
$res = json_decode(file_get_contents('php://input'), true);
}
Let me know if it is unclear as I have been using it in my controllers

Preview post with image before confirming submission to server

I have a page with a form that contains many fields and an image:
<form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data">
<input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFWNJTqNVYiP9">
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material" maxlength="30" style="width:30ch">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color" maxlength="10" style="width:20ch">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" maxlength="500">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input id="modelpic" name="image" type="file">
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show the preview of the image through javascript */
<div class="form-group">
<input id="AddBtn" class="btn btn-default" type="submit" value="Submit">
</form>
here is the javascript that shows the image preview in the form after selection:
$(document).ready(function() {
$('#modelpic').on("change", function () {
//shows image preview in DOM
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(this.files[0]); // read the local file
reader.onloadend = function(){ // show image in div
$('#imagePreview').show().html('<img id="theImage" src="' +this.result+ '" class="img-fluid" alt="Your Image" />');
}
}
})
});
What I need to do is show a preview of the post as it will appear before confirming submission.
How can I do it with jquery? My guess is I also have to modify the action part of the form code action="http://project.dev/model/useradd" in the html to something like self or something? Is it correct?
How do I get the submitted form data along the picture after hitting submit in jquery and use that to output the html to a preview div?
--- I also thinked to send the data to the server, save the image temporarily in public then load it in the preview. The problem is that if I use ajax to intercept the submission the image is not submitted. I think it's a problem of specyfing the data. My JS script code is like this:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
I think this is wrong probably in the datatype or something.

Angularjs Image Upload showing empty nested object

I'm a bit confused how to access file data using with angular from a basic form. I'm following a tut on: (https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs) and youtube (https://www.youtube.com/watch?v=vLHgpOG1cW4). They seem to get it right but when I try things seem to go a different way. Anyways here's my HTML form:
<form>
<div class="form-group">
<label for="name">Full Name</label>
<input type="text" ng-model="customer.name" id="name" class="form-control"/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" ng-model="customer.email" id="name" class="form-control"/>
</div>
<div class="form-group">
<label for="file">Image</label>
<input type="file" file-model="customer.file" id="file" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" ng-click="submit()" class="btn btn-primary">Submit</button>
</div>
</form>
And the Directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
And finally the controller:
app.controller('CustomerController', ['$scope','CustomerService', function($scope, CustomerService){
$scope.customer = {};
CustomerService.save($scope.customer);
}]);
When I {{ customer }} in my view I'm getting something like this:
{"name":"Robert DeNiro","email":"robie#godfather.com","file":{}}
It's that empty last "file":{} file object that's causing me problems getting values to post to server.
Here's my Customer Service code:
var CustomerService = function($resource) {
return $resource('advertisements/:id', { id: '#_id' }, {
update: {
method: 'PUT' // this method issues a PUT request
},
save: {
method: 'post',
transformRequest: angular.identity,
'Content-Type': undefined
}
});
};
CustomerService.$inject = ['$resource'];
app.service('CustomerService', CustomerService);
I'm using Laravel 5.1 and its reporting validation errors 'required' on all fields suggesting there's an empty object sent through. Thanks in advance.
I have added a submit() method in CustomerController like this:
$scope.submit = function(){
var file = $scope.customer.file;
console.log('file is ' );
console.log(file.name);
console.log($scope.customer.file);
console.dir($scope.customer.file);
};
And in there you can see I've tried experimenting with console.log() and console.dir() and i seem to get the results. For example if i console.log($scope.customer) or console.dir($scope.customer) it gives me the nested file object with all file details. And its looking like this:
> Object {name: "robert deniro", email: "robie#godfather.com", file: File}
> Object
Notice file: File Therefore I'm able to access the file contents/object within the submit() like this: console.log(file.name) or console.log(file.type) or console.log(file.size). I don't know why I was missing it all this time. I hope someone learn from my mistake.
May be that form requires the attribute enctype="multipart/form-data".

Send data to PHP with ajax using formdata

SOLUTION: I had to drop the sumbmit button and use a regular button. The rest of this code works. I also dropped the HTML form.
I'm trying to send an image + some text to my php script with ajax using formdata.
This is what i got:
$ajax_uploadImage = function (form)
{
var data = new FormData();
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
$.ajax({
url: '../php/upload_image.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('something');
}
});
}
The form in the function parameters is a normal html form, here is the form in html:
<form enctype="multipart/form-data" id="upload_image">
<label for="title">Title:</label>
<input type="text" id="title" name="title" />
<br />
<label for="comment">Comment:</label>
<input type="text" id="comment" name="comment" />
<br />
<label for="image">Image:</label>
<input type="file" id="image" name="image" />
<br />
<input type="submit" value="Upload picture" name="submit">
<hr />
</form>
The alert in success never triggers, can anyone help?
EDIT: Adding the PHP, even though it doesn't do anything:
<?php echo 'something'; ?>
Right now you are storing a jQuery object in the FormData which cannot work. Use the values of those elements instead. In case of the file input you need to use the File object in the files property of the DOM element:
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
Try adding form action like:
<form enctype="multipart/form-data" id="upload_image" action="upload_image.php">

Categories