I want to get value from file input from angularjs form in laravel, but i can't get the value.
why?
angularjs:
<div ng-controller="UploadImgController" >
<div ng-repeat="image in images">
<img ng-src="{{image.image}}" />
</div>
<form ng-submit="uploadImg()" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="path" id="path" ng-model="addimages.path" accept="image/*" app-filereader>
<input type="text" name="propertyid" ng-model="addimages.propertyid">
<input type="submit" value="Upload Image" name="submit" class="btn btn-primary" >
</form>
</div>
laravel (UploadImgController.php):
public function store()
{
$file = Input::file('path');
echo "file: ".$file;
}
(routes.php):
Route::resource('img','UploadImgController');
I got no value. What should I do? Thank you. :)
I recommend using ng-file-upload.
View
<button ng-file-select ng-model="myFiles" ng-file-change="upload($files)">Upload</button>
Angular JS
var app = angular.module('fileUpload', ['angularFileUpload']);
app.controller('MyCtrl', ['$scope', '$upload', function ($scope, $upload) {
$scope.upload = function (files) {
if (files && files.length){
for (var i = files.length - 1; i >= 0; i--) {
var file = files[i];
$upload.upload({
url: '/upload',
fields: {key: 'value'},
file: file
})
.progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('File upload ' + progressPercentage + "% complete.");
})
.success(function (data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
console.log(data);
});
}
}
};
}
]);
Laravel Route
Route::post('upload', [
'uses' => 'FileUploadController#upload'
]);
Laravel Controller
public function upload() {
$file = \Input::file('file');
return $file;
}
You can pull that off without a plugin actually. I did face a similar problem once and this is how I went about it.
View
<input type="file" name="file" onchange="angular.element(this).scope().uploadImage(this.files)"/>
Angularjs Controller
$scope.uploadavtar = function (files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("/upload-url" + $scope.school.profile.id, fd, {
withCredentials: true,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).then(function successCallback(response) {
$scope.result = response;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
console.log(response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
Routes.php
Route::post('/upload-url', 'UsersController#uploadFile');
Laravel Controller
// Upload files
public function uploadFile(Requests\UpdateuploadfileRequest $request, $id)
{
$extension = Input::file('file')->getClientOriginalExtension();
$fileName = time().'.'.$extension; // renameing image
$destination = 'uploads/img'. $fileName;
move_uploaded_file($_FILES['file']['tmp_name'], $destination);
}
}
Request validation file (UpdateuploadfileRequest.php)
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
];
return $rules;
}
Related
When I try to upload a file on my Symfony API, I have an error from MediaObjectAction.php which is a controller.
This file looks like this :
final class CreateMediaObjectAction extends AbstractController
{
public function __invoke(Request $request): MediaObject
{
$uploadedFile = $request->files->get('file');
if (!$uploadedFile) {
throw new BadRequestHttpException('"file" is required');
}
$mediaObject = new MediaObject();
$mediaObject->file = $uploadedFile;
return $mediaObject;
}
}
and it throws me the error : "file" is required
In the front-end, I use ReactJS and I do a simple file upload with these functions :
const handleFileChange = (event) => {
console.log(event.target.files[0])
setFile({ selectedFile: event.target.files[0], loaded: 0 })
}
const uploadFile = () => {
FileUtils.uploadFile(MEDIA_OBJECT_ENDPOINT, file.selectedFile)
.then((response) => {
console.log(response)
})
const FileUtils = {
uploadFile: async (url, file) => {
const data = new FormData()
data.append('name', 'file')
data.append('file', file)
const response = await api.post(url, data)
return response
},
}
And in html, the file input looks like this :
<input
type="file"
id="file"
name="file"
onChange={handleFileChange}
></input>
As you can see, it is very basic, but it does not work and I cannot figure out why. Do you have an idea of what I miss ?
PS : The function api.post() works very well, the problem does not come from it.
Vue template (File upload): This input field is generated from another module, Where the from generated by drag and drop input field.
<input type="file" #change="uploadFile(data,$event)" class="custom-file-input" id="validatedCustomFile">
Script Vuejs:
data () {
return {
//baseform
baseForm: new Form({
form:this.data ? JSON.parse(this.data.dataForm) : '',
}),
}
},
methods: {
uploadFile(data,e){
let file = e.target.files[0];
data.value = file;
},
// form data submit
formSubmit() {
const config = {
headers: {'Content-Type': 'multipart/form-data'}
}
let formData = new FormData();
formData.append('form',JSON.stringify(this.baseForm.form));
axios.post('/api/order-data',formData, config)
.then((order)=>{
//
}).catch(()=>{
//
})
}
}
Controller: Here is the controller code
$formData = json_decode($request->form, true);
foreach ($formData as $key) {
if($key['field'] == 'fileUpload') {
dd($key['value']);
}
}
I am getting empty value after die dump $key['value']
I have tried majority of other questions here and other solutions and nothing has worked so far.
What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.
Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,
second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.
Route:
Route::post('/upload', 'UploadController#uploadSubmit');
View:
<div>
<input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
<br />
<div id="files_list"></div>
<p id="loading"></p>
<input type="hidden" name="file_ids" id="file_ids" value="" />
</div>
Ajax call:
$(document).ready(function(){
$("input").change(function(){
alert('triggered');
debugger;
$('#fileupload').fileupload({
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
}
dataType: 'json',
add: function (e, data) {
$('#loading').text('Uploading...');
data.submit();
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
if ($('#file_ids').val() != '') {
$('#file_ids').val($('#file_ids').val() + ',');
}
$('#file_ids').val($('#file_ids').val() + file.fileID);
});
$('#loading').text('');
}
});
});
});
});
Controller:
public function uploadSubmit(Request $request){
$files = [];
dd(request());
foreach($learnerFiles as $key => $learnerFile){
if(count($learnerFile) > 0){
$path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
$search = 'public/' ;
$trimmed = str_replace($search, '', $path) ;
//dd($learnerFiles);
$file = FileUpload::create([
'user_id' => $learner->id,
'file_name' => $key,
'path' => $trimmed
]);
}
else{
}
$file_object = new \stdClass();
$file_object->name = $key;
$file_object->size = round(Storage::size($path) / 1024, 2);
$file_object->fileID = $learner->id;
$files[] = $file_object;
}
return response()->json(array('files' => $photos), 200);
}
I'm using the following method to upload images using Ajax call and Laravel back-end.
var uploader = $('#image-uploader[type="file"]');
var data = new FormData();
$.each(uploader.files, function() {
data.append('image[]', this);
});
data.append('_token', $('[name="csrf-token"]').attr('content'));
var url = '/upload'; //Or any target path with post method
$.ajax({
url: url,
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
alert('succeed');
}
});
Consider you can access to image files in server-side using $_POST['image] array.
Hope this helps you.
Why is it the file i upload not reflecting on the request even though the file is uploaded successfully?
HTML
<div id="upload_excel" class="dropzone form-control">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
JS
var baseUrl = "{{ url('/') }}";
var token = "{{ Session::getToken() }}";
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#upload_excel", {
paramName: "file",
acceptedFiles: ".xls,.xlsx",
maxFiles: 1,
maxFilesize: 10,
url: baseUrl + "/upload",
params: {
_token: token
}
});
Controller
class UploadsController extends Controller
{
public function upload(Request $request) {
return $file = $request->all();
}
}
Request Preview
[
Request Response
{"_token":"ePssa9sPZxTcRR0Q4Q8EwWKjODXQ8YpCcH8H9wRP","upload_date":"2016-08-02","file":{}}
Did i miss something or what?
I have a controller like this
public function upload(Request $request) {
// validation etc
// ...
// I have a table and therefore model to list all excels
$excelfile = ExcelFile::fromForm($request->file('file'));
// return whater ...
}
In my ExcelFile Model
protected $baseDir = 'uploads/excels';
public static function fromForm(UploadedFile $file) {
$excelfile = new static;
$name = time() . $file->getClientOriginalName();
$name = preg_replace('/\s+/', '', $name);
$excelfile->path = $excelfile->baseDir . '/' . $name;
$file->move($excelfile->baseDir, $name);
return $excelfile;
}
You will also need to add UploadedFile in your Model
use symfony\Component\HttpFoundation\File\UploadedFile;
My dropzone is defined like this to ensure correct token handling
<form action="/users/{{ $id }}/media/excelupload" id="drop-zone" class="dz dropzone">
{{ csrf_field() }}
</form>
<script>
new Dropzone("#drop-zone", {
maxFilesize: 3, // MB
maxFiles: 10,
dictDefaultMessage: "Upload Excel.",
init: function() {
var known = false;
this.on("success", function(file, responseText) {
// do stuff
});
this.on('error', function() {
// aler stuff
});
this.on("addedfile", function() {
if (this.files[10]!=null){
this.removeFile(this.files[0]);
if (known === false) {
alert('Max. 10 Uploads!')
known = true;
}
}
});
}
});
</script>
I hope this helps
I am trying to upload file to read in php. But, I unable to transmit a file over to the php.
My code was,
HTML Code:
<label>Import</label>
<div class="form-group">
<input type="file" ng-file-select="uploadFile($files)" />
</div>
app.js:
var app = angular.module('myApp','ngRoute','myApp.bulk','ngSanitize','angularFileUpload']);
bulk.js
var bulkApp = angular.module('myApp.bulk', ['ngResource','ngRoute','ngSanitize']);
bulkApp.factory('FileUploadService', function ($http) {
var api = {
uploadFile: function (file, callback) {
alert(file.name);
$http.uploadFile({
url: 'xxx/services.php?upload=1',
file: file
}).progress(function(event) {
console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
}).error(function (data, status, headers, config) {
console.error('Error uploading file')
callback(status);
}).then(function(data, status, headers, config) {
callback(null);
});
}
}
return api;
});
bulkApp.controller('bulkController', function($scope,$rootScope,$filter,FileUploadService) {
var service = FileUploadService;
/**
* Handler to upload a new file to the server.
*/
$scope.uploadFile = function ($files) {
var $file = $files[0];
service.uploadFile($file, function (error) {
if (error) {
alert('There was a problem uploading the file.');
}
// handle successfully-uploaded file
})
}
});
services.php
if(isset($_REQUEST) && isset($_REQUEST['upload']))
{
var_dump($_FILES);
/* read functionality over here */
}
I referred this link
i am getting TypeError: $http.uploadFile is not a function error.
please help. thanks in advance .
use $upload service instead of $http:
bulkApp.factory('FileUploadService', function ($upload) {
var api = {
uploadFile: function (file, callback) {
$upload.upload({
url: 'xxx/services.php?upload=1',
file: file
}).progress(function(event) {
console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
}).error(function (data, status, headers, config) {
console.error('Error uploading file')
callback(status);
}).then(function(data, status, headers, config) {
callback(null);
});
}
}
return api;
});