I am not able to post files using dropzone.js to controller. I have a parameter IEnumerable files. All data can be posted except dropzone files.
My code:
//Html
<div class="jumbotron">
<div class="dropzone" id="dropzoneForm">
<div class="fallback">
<input name="files" type="file" multiple/>
</div>
</div>
</div>
//Javascript:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#dropzoneForm", {
url:'/TravelPlaces/Create',
paramName: 'files',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 25,
maxFiles: 5
});
//Called by submit
function uploadClicked() {
myDropzone.processQueue();
}
//Here is my Controller Code:
// I have two other file uploader in the same form as well.
public ActionResult Create([Bind(Include = "TravelPlaceID,Title,PlaceDescription,Logo,CountryID,State,ProvinceID,DistrictID,Address,Location,OtherMap,ServicesID")] TravelPlace travelPlace,HttpPostedFileBase Logo,HttpPostedFileBase OtherMap,IEnumerable<HttpPostedFileBase> files)
{
foreach (var p in files)
{
var z = p.FileName;
}
}
Related
I have a block of code which would upload the file into the Google Drive. My main issue here is that when the user clicks on the upload button, the MD5 hash of the file will be checked and compared with the MD5 hashes of other files in the Google Drive and if there is a duplicate, then a message pop-up should be displayed stating that the file is a duplicated file and the user would need to reupload the file again.
This is from my GetGoogleDrive.cshtml file.
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<label for="file">Upload file:</label>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" id="fileUpload" />
<script>
$('#fileUpload').click(function (e) {
if ($('#file').val() === "") {
Swal.fire({
title: 'Nothing',
text: 'No file selected',
type: 'error',
confirmButtonText: 'Again!!',
timer: 4000
})
}
else {
Swal.fire({
title: 'Wait awhile...',
text: 'File will be uploaded shortly',
type: 'success',
confirmButtonText: 'Okay, cool',
timer: 4000
})
}
});
</script>
The following code is for my upload file controller class.
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
GoogleDriveFilesRepository.FileUpload(file);
return RedirectToAction("GetGoogleDriveFiles");
}
This is the code for my Google Drive Files model class.
public static void FileUpload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
DriveService service = GetService();
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
HashGenerator(path);
compareHash(HashGenerator(path));
var FileMetaData = new Google.Apis.Drive.v3.Data.File();
FileMetaData.Name = Path.GetFileName(file.FileName);
FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
{
request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
request.Fields = "id";
request.Upload();
}
}
}
Where should I generate the MD5 hash value of the file? In the C# or the JS?
i want to fetch the file based on my applications_id and i want to see it in the bootstrap file input and i want to delete it and replace with a new file. how can i do it. below is what i have tried .can anyone help me .i am stuck.
this is my contoller function SoleProprietorController.php
public function uploadImages(Request $request, $applications_id)
{
$applications = new Applications;
// $KRAPIN = Input::get('KRA_unique_field');
$applications_id = Input::get('applications_id_unique_field');
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
// request()->breg_cert->move(public_path('breg_cert'), $imgName);
// $imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$imgName = basename($request->breg_cert->move(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
return response()->json(['uploaded' => '/breg_cert/'.$imgName]);
}
}
this my web.php
Route::post('/uploadImages/{applications_id}', 'SoleProprietorController#uploadImages')->name('home');
this is my bootstrap file in my blade
<div class="col-md-4 mb-3">
<label for="validationServer023">Upload Business Registration Document</label>
<div class="form-group">
<div content="{{ csrf_token() }}" class="input-group input-file" name="Fichier1">
<input id="file-0a" name="breg_cert" value="" class="file" accept="text" type="file"> <br />
</div>
</div>
</div>
<script>
$("#file-0a").fileinput({
initialPreview: [
"<img src='/images/php' class='file-preview-image'>",
],
showUpload: true,
showRemove: true,
showCaption: true,
showPreview: true,
showClose: false,
autoOrientImage: true,
showUploadedThumbs: false,
uploadAsync: false,
uploadUrlThumb: false,
deleteUrl: "/public/KFS_Business_Registration_Certificates",
uploadUrl: "/uploadImages/{applications_id}",
// dataUrl: "/breg_cert/",
// uploadUrl: '/public/KFS_Business_Registration_Certificates', // you must set a valid URL here else you will get an error
theme: 'fa',
uploadExtraData: function() {
return {
_token: "{{ csrf_token() }}",
};
},
allowedFileExtensions: ['jpg', 'png', 'gif', 'pdf', 'jpeg'],
overwriteInitial: false,
maxFileSize: 500,
maxFilesNum: 10,
//allowedFileTypes: ['image', 'video', 'flash'],
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
</script>
1.Use code like this to store uploaded file and associate it with your Applications
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
$imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
}
https://laravel.com/docs/5.8/requests#storing-uploaded-files
To store an uploaded file, you will typically use one of your configured filesystems. The UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.
The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a file name, since a unique ID will automatically be generated to serve as the file name.
To handle delete/replace create a corresponding controller method and POST route and then provide the route to deleteUrl option.
In the above method check the filename associated and unlink it. (actual code depends on what dd($request); output)
To show stored image as preview add option to $("#file-0a").fileinput({
initialPreview: [
"<img src='/images/path-to.jpg' class='file-preview-image'>",
],
I am using Fine Uploader for uploading multiple files.
It's working fine.
But i want a little bit change.
I have a file name upload.php in which i have written a file uploading script in database.
I just want that after hitting upload button the request will go to my upload.php file and the files will be uploaded accordingly.
How i can achieve this ?
index.php
<script type="text/template" id="qq-template-manual-trigger">
<div class="buttons">
<div class="qq-upload-button-selector qq-upload-button">
<div>Select files</div>
</div>
<button type="button" id="trigger-upload" class="btn btn-primary">
<i class="icon-upload icon-white"></i> Upload
</button>
</div>
</script>
Javascript
<script>
var manualUploader = new qq.FineUploader({
element: document.getElementById('fine-uploader-manual-trigger'),
template: 'qq-template-manual-trigger',
request: {
endpoint: '/server/upload.php'
},
thumbnails: {
placeholders: {
waitingPath: '/source/placeholders/waiting-generic.png',
notAvailablePath: '/source/placeholders/not_available-generic.png'
}
},
autoUpload: false,
debug: true
});
qq(document.getElementById("trigger-upload")).attach("click", function() {
manualUploader.uploadStoredFiles();
});
</script>
upload.php
<?php
require_once './include/db_connection.php';
if(!empty($_FILES)){
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
//insert file information into db table
$sql = mysqli_query($link,"INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
}
else
{
echo 'Query not working';
}
}
I'm pretty new with programming. I'm learning how to use CollectionFS with Angular, but cant get the files back from DB. Here is my code:
Html:
<body>
<div class="container" ng-app="upload">
<div ng-controller="uploadCtrl">
<form id="uploadForm" >
<input type="file" id="file">
<button ng-click="uploadPhoto()">Pobierz</button>
</form>
<ul>
<li ng-repeat="zdjecie in zdjecia">
<img ng-src="{{ zdjecie.url }}" />
</li>
</ul>
</div>
</div>
</body>
angular:
angular.module('upload', ['angular-meteor']);
angular.module('upload').controller('uploadCtrl', ['$scope', '$meteor',
function ($scope, $meteor) {
$scope.zdjecia = $meteor.collectionFS(Zdjecia, false, Zdjecia);
var fileInput = document.getElementById('file');
$scope.uploadPhoto = function () {
var file = fileInput.files[0];
$scope.zdjecia.save(file);
};
}]);
backend:
Zdjecia = new FS.Collection("zdjecia", {
stores: [
new FS.Store.FileSystem("zdjecia"), { path : '~/zdjecia'}
]
});
if (Meteor.isServer) {
Zdjecia.allow({
insert: function () {
return true;
}
});
}
I really can't get, how to grab a file back from the database, they also ain’t appear in the path folder.
I'm a beginner to angular.js but I have a good grasp of the basics.
What I am looking to do is upload a file and some form data as multipart form data. I read that this isn't a feature of angular, however 3rd party libraries can get this done. I've cloned angular-file-upload via git, however I am still unable to post a simple form and a file.
Can someone please provide an example, html and js of how to do this?
First of all
You don't need any special changes in the structure. I mean: html input tags.
<input accept="image/*" name="file" ng-value="fileToUpload"
value="{{fileToUpload}}" file-model="fileToUpload"
set-file-data="fileToUpload = value;"
type="file" id="my_file" />
1.2 create own directive,
.directive("fileModel",function() {
return {
restrict: 'EA',
scope: {
setFileData: "&"
},
link: function(scope, ele, attrs) {
ele.on('change', function() {
scope.$apply(function() {
var val = ele[0].files[0];
scope.setFileData({ value: val });
});
});
}
}
})
In module with $httpProvider add dependency like ( Accept, Content-Type etc) with multipart/form-data. (Suggestion would be, accept response in json format)
For e.g:
$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';
Then create separate function in controller to handle form submit call.
like for e.g below code:
In service function handle "responseType" param purposely so that server should not throw "byteerror".
transformRequest, to modify request format with attached identity.
withCredentials : false, for HTTP authentication information.
in controller:
// code this accordingly, so that your file object
// will be picked up in service call below.
fileUpload.uploadFileToUrl(file);
in service:
.service('fileUpload', ['$http', 'ajaxService',
function($http, ajaxService) {
this.uploadFileToUrl = function(data) {
var data = {}; //file object
var fd = new FormData();
fd.append('file', data.file);
$http.post("endpoint server path to whom sending file", fd, {
withCredentials: false,
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity,
params: {
fd
},
responseType: "arraybuffer"
})
.then(function(response) {
var data = response.data;
var status = response.status;
console.log(data);
if (status == 200 || status == 202) //do whatever in success
else // handle error in else if needed
})
.catch(function(error) {
console.log(error.status);
// handle else calls
});
}
}
}])
<script src="//unpkg.com/angular/angular.js"></script>
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
It is more efficient to send the files directly.
The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
Doing Multiple $http.post Requests Directly from a FileList
$scope.upload = function(url, fileList) {
var config = {
headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.
Working Demo of "select-ng-files" Directive that Works with ng-model1
The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileList" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileList">
{{file.name}}
</div>
</body>
You can check out this method for sending image and form data altogether
<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
<label for="image_name">Image Name:</label>
<input type="text" placeholder="Image name" ng-model="fileName" class="form-control" required>
<br>
<br>
<input id="file_src" type="file" accept="image/jpeg" file-input="files" >
<br>
{{file_name}}
<img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
<hr>
<button class="btn btn-info" ng-click="uploadFile()">Upload</button>
<br>
<div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
<strong> {{response_msg}} </strong>
</div>
<div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
</div>
Angular JS Code
var app = angular.module("myApp", []);
app.directive("fileInput", function($parse){
return{
link: function($scope, element, attrs){
element.on("change", function(event){
var files = event.target.files;
$parse(attrs.fileInput).assign($scope, element[0].files);
$scope.$apply();
});
}
}
});
app.controller("myCtrl", function($scope, $http){
$scope.IsVisible = false;
$scope.uploadFile = function(){
var form_data = new FormData();
angular.forEach($scope.files, function(file){
form_data.append('file', file); //form file
form_data.append('file_Name',$scope.fileName); //form text data
});
$http.post('upload.php', form_data,
{
//'file_Name':$scope.file_name;
transformRequest: angular.identity,
headers: {'Content-Type': undefined,'Process-Data': false}
}).success(function(response){
$scope.IsVisible = $scope.IsVisible = true;
$scope.response_msg=response;
// alert(response);
// $scope.select();
});
}
});