<input type="file" name="default_image" id="imgInp" value="{{$property->default_image}}">
<div class="dropzone_upload">
<div class="dz-message" data-dz-message>
<span>
<img src='/assets/home/img/cloud_upload.png'/><br/>DRAG AND DROP IMAGES HERE <br/> <span class='or'>or</span> <br/> <a href='javascript:void(0)' class='upload_images'>UPLOAD IMAGES</a>
</span>
</div>
</div>
Now i have a problem when i upload default image and images in dropzone it mix those two so everything puts in default_image[].
Any suggestion how can i fix that?
When i do like this it say that image must be a type of jpeg,bmp,png:
$this->validate($request,[
'default_image' => 'mimes:jpeg,bmp,png|max:2000'
]);
This is my config for dropzone:
Dropzone.options.myDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
addRemoveLinks: true,
previewsContainer: '.dropzone-previews',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
maxFiles: 10,
autoDiscover:false,
paramName:'gallery_images',
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
if (myDropzone.getQueuedFiles().length > 0) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
console.log('sendingmultiple');
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
console.log('successmultiple error',response);
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
$("html, body").animate({ scrollTop: 0 }, "slow");
$("#resultMsg").css('display', 'block').text(response.successMsg);
});
this.on("errormultiple", function(files, response) {
console.log('response error',response);
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
};
You need to use the rule like this:
$this->validate($request,[
'default_image.*' => 'mimes:jpeg,bmp,png|max:2000'
]);
For more details: https://laravel.com/docs/5.4/validation#validating-arrays
Related
I want to test the response in the console log. I am using the google inspect tool. I can't see any response in Network>>XHR. But I have seen that "Form submission canceled because the form is not connected" in console. The sample screen inspect tool screen I can't trace the problem actually where. I am following a course video about laravel and vue. Thanks in advance for your time.
Form
<form v-if="editing" #submit.prevent="update">
<div class="form-group">
<textarea rows="10" v-model="body" class="form-control"></textarea>
</div>
<button #click="editing = false">Update</button>
<button #click="editing = false">Cancel</button>
</form>
in Controller
if ($request->expectsJson()) {
return response()->json([
'message' => 'Answer updated!',
'body_html'
]);
}
Vue.JS
<script>
export default {
props: ['answer'],
data () {
return {
editing: false,
body: this.answer.body,
bodyHtml: this.answer.body_html,
id: this.answer.id,
questionId: this.answer.question_id
}
},
methods: {
update () {
axios.patch(`/questions/${this.questionId}/answers/${this.id}`, {
body: this.body
})
.then(res => {
console.log(res);
this.editing = false;
})
.catch(err => {
console.log("something went wrong");
});
}
}
}
</script>
The form is by default hidden. It appears only when clicking on the Edit button. The only problem is to submit the form. ErrorMessage: Form submission canceled because the form is not connected
You have v-if="editing" in your form set to false. It should be true, because form has to exist on submit. You are removing your form from DOM. Also move this.editing to finally() block in axios call.
I want to Cancel the file uploading on click of cancel button.
means I want to trigger the onCancel(e) event on click of my cancel button
My code is,
#(Html.Kendo().Upload()
.Name("files")
.Multiple(false)
.Async(a => a
.Save("UploadArtifactFile", "PP", new { TeacherEvalID = ViewBag.TeacherEvalID, ObservationID = ViewBag.ObservationID, Accountid = ViewBag.AccountID })
.AutoUpload(false)
.RemoveField("")
)
.Events(events => events
.Success("onSuccess")
.Select("onSelect")
.Error("onUploadError")
.Upload("onUpload")
.Cancel("onCancel")
.Remove("onRemove")
)
On cancel event is work as expected,
function onCancel(e) {
//Array with information about the uploaded files
var files = e.files;
e.preventDefault();
}
I want to do the same thing for Cancel Button and on click of cancel button i have write code as,
function setNewArtifact() {
var upload = $("#files").data("kendoUpload");
//detach events and prepare for safe removal
//upload.destroy();
$(".k-upload-files.k-reset").find("li").remove();
$('#lblArtifactFileName').val("");
$('#lblArtifactFileName').hide();
//hdnArtifactUploadIsAddOrEdit :1 for new artifact (Add)
$('#hdnArtifactUploadIsAddOrEdit').val("1");
$('#txtArtifactDescription').val("");
$('#lblArtifactFileName').hide();
$('#btnModifyArtifact').css("display", "none");
$('.k-upload-selected').css("display", "none");
//on click of cancel hide the uploading and uploaded status
$(".k-dropzone").find("strong").css("display","none");
$(".k-upload-status.k-upload-status-total").find("span").css("display","none");
$.extend(upload.options.localization, {
headerStatusUploading: "",
headerStatusUploaded: ""
});
}
There is any way to do this?
Please help...
You can trigger upload cancel event:
$(document).ready(function() {
$("#files").kendoUpload({
async: {
saveUrl: "save",
removeUrl: "remove",
autoUpload: true
},
cancel: function(e) {
alert("cancel");
}
});
$("#button").click(function(e) {
$("#files").data("kendoUpload").trigger("cancel");
});
});
<input name="files" id="files" type="file" />
<button id="button">Cancel</button>
My code is to realize a paginate page like this example, https://github.com/bitovi/canjs/blob/master/component/examples/paginate.html .
I found the {#messages}...{/messages} in message.mustache template was not been inserted into page , while messagelist component inserted event has been triggered, so i can not do any binding to {#messages} dom in the event, because it ‘not exists in the page.
Are there other ways to fix this problem?
The Templates:
message_list.mustache:
<app>
<messagelist deferredData='messagesDeferred'></messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>
message.mustache:
{#messages}}
<dl>
<dt>.....</dt>
<dd>....</dd>
</dl>
{/messages}
The Component:
can.Component.extend({
tag: "messagelist",
template: can.view('/static/web/tpl/mobile/message.mustache'), // to load message template
scope: {
messages: [],
waiting: true,
},
events: {
init: function () {
this.update();
},
"{scope} deferreddata": "update",
update: function () {
var deferred = this.scope.attr('deferreddata'),
scope = this.scope,
el = this.element;
if (can.isDeferred(deferred)) {
this.scope.attr("waiting", true);
deferred.then(function (messages) {
scope.attr('messages').replace(messages);
});
} else {
scope.attr('messages').attr(deferred, true);
}
},
"{messages} change": function () {
this.scope.attr("waiting", false);
},
inserted: function(){
// can't operate the dom in message.mustache template
}
}
});
//to load component template
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
$("#message-list").html(content)
});
I have solved the problem, but not the best, Maybe someone have a better way.
I changed my template, add a new component called <messageitem>
<messageitem> will load another template: message.mustache
Every <messageitem> will trigger inserted event when inserted into <messagelist>
The new component:
can.Component.extend({
tag: "messageitem",
template:can.view('/static/web/tpl/mobile/message.mustache'),
events: {
inserted: function(el, ev){
// Can-click can not satisfy my needs,
// because i call the third-party module to bind click event
// this module will be called repeatedly, not the best way
reloadModules(['accordion']);
}
}
});
// To load message_list.mustache
can.view("/static/web/tpl/mobile/message_list.mustache",{}, function(content){
$("#message-list").html(content)});
Static html:
<body>
<div id="message-list">
....
</div>
</body>
message_list.mustache:
<app>
<messagelist deferredData='messagesDeferred'>
{{#messages}}
<messageitem></messageitem>
{{/messages}}
</messagelist>
<next-prev paginate='paginate'></next-prev>
<page-count page='paginate.page' count='paginate.pageCount'></page-count>
</app>
message.mustache:
<dl class="am-accordion-item" >
...
</dl>
I use dropzone with CI, i don't know how to display error message and custom message when upload false, this is my script
Dropzone.autoDiscover = false;
try {
var myDropzone = new Dropzone("#adminform" , {
paramName: "filename", // The name that will be used to transfer the file
maxFilesize: 0.5, // MB
url: window.location.href,
addRemoveLinks : true,
dictDefaultMessage :
'<span class="bigger-150 bolder"><i class="ace-icon fa fa-caret-right red"></i> Drop files</span> to upload \
<span class="smaller-80 grey">(or click)</span> <br /> \
<i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>',
dictResponseError: 'Error while uploading file!',
//change the previewTemplate to use Bootstrap progress bars
previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n <div class=\"dz-success-mark\"><span></span></div>\n <div class=\"dz-error-mark\"><span></span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
});
}
catch(e) {
alert('Dropzone does not support older browsers!');
}
And PHP return 400:
$this->output->set_header("HTTP/1.0 400 Bad Request");
But when i hover image it's display [object Object] but message is:
dictResponseError: 'Error while uploading file!'
For anyone in need:
You can return a response message from the server using echo. Then in the js code add an error event handler
PHP
header("HTTP/1.0 400 Bad Request");
echo "Ups error message";
JS
this.on('error', function(file, response) {
$(file.previewElement).find('.dz-error-message').text(response);
});
For me this code finally worked, used as a dropzone option:
error: function(file, message) {
$(file.previewElement).addClass("dz-error").find('.dz-error-message').text(message.Message);
}
I used message.Message since the ASP.net WebAPI returns a JSON object, but not with the required "error" key.
You can simply echo back the message from server via PHP file
if($file_uploaded == true)
{
//perform operations on valid upload
} else {
//upload failed, echo back negative response to dropzone.js
$this->output->set_header("HTTP/1.0 400 Bad Request");
echo "Error uploading file";
}
While your HTML file can look like:
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
paramName: "icon_image", // The name that will be used to transfer the file
maxFilesize: 2, // MB
init: function() {
this.on("error", function(file, response) {
// do stuff here.
alert(response);
});
}
};
</script>
Hope it helps :)
I need to upload multiple files as one request.
For example, i have two required files (.csv & .ctl) that I need to save.
Basically on the server side, I'm reading the .csv file and checking it against the .ctl file. If certain criteria doesn't match, I don't need to upload it. I'm not sure how or need to update the 'upload' method to read the filenames[]. Nor if I need to update this line "uploader.fineUploader('uploadStoredFiles');" to now accept the filenames[] after the user clicks "Upload now."
<script type="text/javascript">
$(document).ready(function () {
var filenames = [];
var uploader = $("#fine-uploader").fineUploader({
request: {
endpoint: '<%= ResolveUrl("~/Handler/UploadHandler.ashx")%>'
},
autoUpload: false,
text: {
uploadButton: '<span class="glyphicon glyphicon-plus"></span> Select Files'
},
validation: {
allowedExtensions: ['csv', 'ctl']
},
showMessage: function (message) {
// Using Bootstrap's classes
$('#fine-uploader').append('<div class="alert alert-danger">' + message + '</div>');
}
}).on('validate', function (event, fileData) {
return $.inArray(fileData.name, filenames) < 0;
}).on('submitted', function (event, fileId, fileName) {
filenames.push(fileName);
}).on('upload', function (event, fileId, fileName) {
var fileItemContainer = $(this).fineUploader('getItemByFileId', fileId);
$(this).fineUploader('setParams', { uploadType: 'VendorFileType', vendorId: '<%=vendorDropdownList1.CurrentVendorID %>' }, fileId);
}).on('complete', function (event, fileName, fileName, responseJSON) {
if (responseJSON.success) {
var div = document.getElementById('fine-uploader-status');
div.innerHTML = 'Upload process complete.';
}
else {
var div = document.getElementById('fine-uploader-status');
div.innerHTML = 'Upload denied.';
}
});
$('#uploadSelectedFiles').click(function () {
uploader.fineUploader('uploadStoredFiles');
});
});
</script>
//here's the aspx side.
<div id="fine-uploader">
</div>
<div id="fine-uploader-status">
</div>
<button id="uploadSelectedFiles" class="btn btn-primary">
<span class="glyphicon glyphicon-upload"></span>Upload now</button>
Fine Uploader does not support sending multiple files in a single request. This complicates the code unnecessarily and would break some existing features. Each file is sent in a separate request. You say you are performing some server-side checks to prevent uploads, but the files have already been uploaded by the time your server is able to perform these comparisons anyway. It's not clear from your question why you need to upload multiple files in a single request, or what benefit this gives you. If you clarify, perhaps I can provide alternate suggestions.