Form data not appending values/image using Angular 4 - php

Hello friends I created a project in angular 4 I want to upload an image and sent request to the PHP file but form-data can't append values and images.
please help me
I include FormGroup, FormControl, FormBuilder, Validators, Http
const Image = this.com_Image.nativeElement;
if (Image.files && Image.files[0]) {
this.comImageFile = Image.files[0];
}
const ImageFile: File = this.comImageFile;
// [enter image description here][1]
let formData = new FormData();
formData.append('companyName', value.companyName);
formData.append('username', value.username);
formData.append('uploadFile', ImageFile, ImageFile.name);
console.log(formData);

Html
<input #fileSelect type="file" class="form-control" (change)="onFileChanged($event)" accept=".jpg, .png"/>
component
export class FileUploadComponent {
#ViewChild('fileSelect') fileSelectInput: ElementRef;
fileToUpload: any;
onFileChanged(event) {
// https://stackoverflow.com/questions/13602039/e-srcelement-is-undefined-in-firefox
this.fileToUpload = (event.srcElement || event.target).files;
let formData: FormData = new FormData();
formData.append('file', this.fileToUpload[0]);
this.createOrUpdateResource(formData);
}
// https://stackoverflow.com/questions/48059121/angular4-file-upload-put-request-fails,
so making this POST
private createOrUpdateResource(formData: FormData) {
this.http.post<any>(`http://localhost:8080/upload`, formData).subscribe((res) => {
//success
}, error => {
//error
});
}
}

Have you tried to pass only name and value for the image?
For file management (in general) this has worked for me:
formData.append('uploadFile', ImageFile);

Related

Vue-Laravel file formdata always empty

I'm trying to upload a file to a laravel backend via axios.
When a user clicks on the file input I get the file object, append it to the formData object post it to the backend, but for some reason, when I try to get the file on the backend I get an empty array.
here is my code:
<template>
<div>
<input type="file" #change="uploadFile" ref="file">
<button #click="submitFile">Upload!</button>
</div>
uploadFile(){
this.Images = this.$refs.file.files[0];
const formData = new FormData();
formData.append('file', this.Images);
const headers = { 'Content-Type': 'multipart/form-data' };
axios.post(this.baseUrl+'test-file-uploads', formData, { headers }).then((res) => {
res.data.files; // binary representation of the file
res.status; // HTTP status
});
}
public function testUploads(Request $request){
return [$request->file('file')];
return $this->uploadFiles($request,108,'props_and_set');
}
Use $request->hasFile('file') to see if the backend is able to get the file from the front end and then call the storage methods on the file.

How to receive $ FILES in PHP from Ionic?

I'm using FormData to send a file from ionic with angular to PHP, but in the PHP backend when you make var dump $_FILES appear empty.
This is my code in .ts:
file: File;
changeListener($event): void {
this.file = $event.target.files[0];
console.info(this.file); //First console info
const formData = new FormData();
const blobFile = new Blob([this.file], { type: this.file.type });
formData.append("file", blobFile, "filename");
this.myService.testing(formData).subscribe( resp => {
},(error)=>{
console.info(error);
})
}
In the service:
testing(data) {
return this.http.post(url, body, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
}
The PHP Backed :
$postdata = file_get_contents("php://input"); // this shows me the contents of the file
var_dump($_FILES); // returns an empty array
So, what's my mistake? Am I sending badly from Ionic or am I getting bad in PHP ?
I'm using codeigniter 3
Thanks !

Multiple Files upload Angular + Laravel

I'm working with Angular. I've to upload multiple images on via an API (made/written in Laravel).
The following body is accepted by the api
portfolio_id: 2
portfolio_image: [ {file1}, {file2} ] //Accepts in this format. File Objects in an array
My angular code is:
HTML
<div class="col-lg-12">
<label class="file-upload-label">Upload Profile Picture</label>
<input multiple (change)="fileSelected($event)" type="file" id="file" name="profile_pic"/>
<label for="file" class="btn-2">Upload</label>
</div>
Component.ts
selectedFile;
fileSelected(event) {
console.log(event);
this.selectedFile = <File>event.target.files;
console.log("Selected Files are:",this.selectedFile)
}
On button submit I'm running the following function from component.ts file:
portfolioImage(){
const formData = new FormData();
formData.append("portfolio_id", this.portfolioId);
formData.append("portfolio_image", this.selectedFile)
this.httpClient.post(this.URL, formData, httpOptionsMulti).subscribe(res => {
console.log(res);
alert('Files uploaded Successfully!');
})
}
Console Output: On file selection change event I see the following in console.log
FileList [ File, File ]
Upon expanding the array I see the following:
FileList(2)
0: File { name: "1.jpg", lastModified: 1578490559152, size: 317383, … }
1: File { name: "2.jpg", lastModified: 1578490599778, size: 288174, … }
length: 2
Issue:
Up on submission I see nothing in params on the network tab although I do get a images uploaded successfully message.
Things I've tried
I tried to upload via loop and changed the fileSelected(event) function to:
myFiles:string [] = [];
fileSelected(event) {
for (var i = 0; i < event.target.files.length; i++) {
this.myFiles.push(event.target.files[i]);
}
}
and upload function to:
portfolioImage(){
console.log("myfile",this.myFiles);
const formData = new FormData();
formData.append("portfolio_id", this.portfolioId);
for(var i = 0; i < this.myFiles.length; i++) {
formData.append("portfolio_image", this.myFiles[i]);
}
this.httpClient.post(this.URL, formData, httpOptionsMulti).subscribe(res => {
console.log(res);
alert('Files uploaded Successfully!');
})
}
But still no luck.
Summary: How to upload multiple files using angular on frontend and laravel api on backend. The laravel api accepts the files as objects in array: [ {file}, {file} ].
Any help will be highly appreciated. Thank you.
You did a little mistake in your upload function, consider the given
portfolioImage(){
const formData = new FormData();
formData.append("portfolio_id", this.portfolioId);
for(var i = 0; i < this.myFiles.length; i++) {
formData.append("portfolio_image[]", this.myFiles[i]);
}
this.httpClient.post(this.URL, formData, httpOptionsMulti).subscribe(res => {
console.log(res);
alert('Files uploaded Successfully!');
})
}
The portfolio_image should be used as given to make it multiple file array in formData. from your Laravel controller function, use as given to check uploaded temp files.
public function uploader(Request $request){
$data = [
$request->allFiles(),
];
return response()->json($data);
}

Laravel How to create and download PDF from view on same route

I have a laravel-application where I want to generate a PDF from the values, the user has entered in some input fields. So when the user has entered the data, he clicks a button which generates the PDF and downloads it immediately afterwards automatically. All this should happen on the same route/view. The PDF should not be stored somewhere.
So right now, when I click the button, the entered Data gets through, e.g. stored in the DB, and it seems that a PDF is created, but I can't see or find it, and my browser does not inform me that there is a PDF available for download.
Before I started, I installed the laravel-dompdf-plugin, and followed the instructions.
So my route look like this
Route::view('formpage', 'app.statement')->name('statement'); // The blade view with the Form
Route::post('statement', 'MyController#generatePDF')->name('generatePDF'); // this is where I post the form
This is my controller
use PDF;
class MyController extends Controller {
public function generatePDF(Request $request){
$statement = Statement::create([
'name' => $validated['name'],
'email' => $validated['email'],
'phone' => $validated['phone'],
'declaration_date' => $validated['declaration_date'],
]);
$pdf = PDF::loadView('pdf.statement', $statement);
return $pdf->download('File__'.$statement->name.'.pdf');
}
}
I posting the form with javascript by using axios by simply doing this:
$('#submitBtn').click(function(e) {
const formData = new FormData();
formData.append(
"name",
$("#statement")
.find('input[name="name"]')
.val()
);
...etc with all other fields
axios.post($("#statement form").attr("action"), formData)
.then(response => {
$('#submitBtn')
.attr("disabled", "disabled")
.addClass("disabled")
.html('<i class="fas fa-fw fa-check"></i> Success'); */
$("#statement form")[0].reset();
})
.catch(error => {
console.log("ERR: ", error); // DEBUG
$("#statement .text-danger").show();
$('#sworn-statement button[type="submit"]')
.removeAttr("disabled")
.removeClass("disabled")
.html("Send");
});
}
What am I doing wrong?
UPDATE
I tried to do this:
const FileDownload = require("js-file-download");
axios.post($("#statement form").attr("action"), formData)
.then(response => {
FileDownload(response.data,"File.pdf");
}).catch(error => {
console.log('error:', error);
});
which gives me a blank page.
So as I said in the comments your problem is that the file is in the response you get from the axios POST request. If you don't handle the filedownload after you get the response nothing will happen.
You can use the js-file-download module. After you've installed this module you can modify your code to something like this:
const FileDownload = require('js-file-download');
axios.get(YOUR_URL)
.then((response) => {
FileDownload(response.data, YOUR_FILE_NAME);
});
There's also an another solution with JQuery which I got from that answer:
$.ajax({
type: "POST",
url: url,
data: params,
success: function(response, status, xhr) {
// check for a filename
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
});
Just replace the url and params attributes with your stuff. This creates also a POST request and handles the incomming PDF file as filedownload after the response arrives.

How to pass image in fetch and save the same in php action to upload t to server?

How to upload and handle image in react native and php?
React-native code:
let img = new FormData();
img.append('file', {
filename: 'image.jpg',
filepath: this.state.image.uri,
contentType: 'image/jpeg',
});
Fetch(`action url?f=createComplaint&otp_code=${this.props.OTPInputText}&cp_phone_no=${this.props.phno}&cp_relationship=${this.props.Relationship}&cp_name=${this.props.Name}&cp_email_id=${this.props.email}
&cp_address=${this.props.address}&cp_complaint_type=${this.props.complianttype}&cp_district=${this.props.location}&cp_compliant_details=${this.props.summary}&otp_code=${this.props.OTPInputText}&cp_resp_name=${this.props.RName}&cp_resp_phone_no=${this.props.Rphno}&cp_resp_email_id=${this.props.Remail}&cp_resp_address=${this.props.address}&cd_name=${this.state.CName}
&cd_gender=${this.state.cGender}+&cd_age=${this.state.cAge}&cd_indentification=${this.state.cIDMark}&cd_photo=${img}`)
PHP Code:
if(isset($_POST)){
$addphoto= explode(".",basename($_FILES['cd_photo']['name']));
$cd_photo = date('Ymdhis').rand(0,999).".".$addphoto[1];
$pathPhoto = '../child_photos/'.$cd_photo;
if(move_uploaded_file($_FILES['cd_photo']['tmp_name'], $pathPhoto)) {
}
I get [object][object] in my url for img

Categories