Kendo Async Upload : File displays even after clicking Remove - asp.net-mvc-4

I am uploading files through Kendo Upload. On uploading a file and then clicking on remove, the RemoveCircular method of controller is called and it duly deletes the file from server.
However the Filename and Remove button are still displayed though they should be removed as well.
Is there anything I'm missing here? Thanks for help.
The code in .cshtml is as below.
<div class="controls-trck">
#(Html.Kendo().Upload()
Name("UploadCircular")
.HtmlAttributes(new { style = "width:220px" })
.Multiple(false)
.Async(a => a
.Save("SaveCircular", "DB0010062")
.Remove("RemoveCircular", "DB0010062")
.AutoUpload(false)
)
)
</div>
Code in Controller:
public ActionResult RemoveCircular(string[] fileNames)
{
foreach (var fullName in fileNames)
{
//Delete Files
}
return Content("");
}

It looks like empty response is treated like as an unsuccessful response. Try to return empty JSON instead.

Related

Fileinput issue in ActiveForm when updating via Yii 2

I am using Yii2 framwork. My file upload function worked well when I upload a single img, while when I click the posed article and I only want to update the post again(Suppose I didn't want to update the img, I only want to update other contents). But I found my uploaded file were replaced with an empty value(varchar type) when I click view. my uploaded img can't show out.
I do tried to fixed by myself as below, But the existing file value can't be saved when I click the submit button.
<?php
if (($post->file) != "") {
echo $form->field($post, 'file')->textInput()->hint('My currently uploaded file')->label('My Photo') ;
}
else{
echo $form->field($post, 'file')->fileInput()->hint('To upload a new file')->label('My Photo') ;
}
?>
When I click submit button, my existing file was gone.
Is there any good way to fix it.
Thanks for your opinions in advance.
Use another variable in your model for upload a file.
For example use file_field name for get file from submitted and store in file field.
class PostModel extends Model
{
/**
*
* #var UploadedFile
*/
public $file_field;
public function rules() {
return [
['file_field', 'file'],
];
}
}
echo $form->field($post, 'file_field')->fileInput()->hint('To upload a new file')->label('My Photo') ;
$post->file_field = UploadedFile::getInstance($post, 'file_field');
For upload new file check the file_field:
if ($post->file_field) {
// $post->file old file
// Save $post->file_field and store name in $post->file
}
Add a rule to your model rules:
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
and check for an empty upload in your controller:
if (Yii::$app->request->isPost) {
$ok = true;
// process your other fields...
...
// process image file only if there is one
$post->file= UploadedFile::getInstance($post, 'file');
if ($post->file && $post->upload()) {
}
if ($ok) {
return $this->redirect(...);
}
}
See Yii2 docs and the Yii2 guide for detailed infos about file upload.

How to download file from Sanity via HTTP?

I would like to know if there is possibility to download file from Sanity with HTTP request?
I only have reference ID:
{
file: {
asset: {
_ref: "file-fxxxxxxxxxxxxxxxxxxxx-xlsx"
_type: "reference"
}
}
}
I would like to do this is this scenario:
<a href="https://cdn.sanity.io/assets/clientID/dataset/file-xxxxxxxxxxx-xlsx">
Download File
</a>
You can, indeed 🎉 With a bit of custom code you can do it just from the _ref, which is the file document's _id
Creating the URL from the _ref/_id of the file
The _ref/_id structure is something like this: file-{ID}-{EXTENSION} (example: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3).
With this, you can generate the downloadable URL, which has the following structure: https://cdn.sanity.io/files/{PROJECT_ID}/{DATASET}/{ID_OF_FILE}.{EXTENSION}. Here's some pseudo Javascript code for the operation:
const getUrlFromId = ref => {
// Example ref: file-207fd9951e759130053d37cf0a558ffe84ddd1c9-mp3
// We don't need the first part, unless we're using the same function for files and images
const [_file, id, extension] = ref.split('-');
return `https://cdn.sanity.io/files/${PROJECT_ID}/${DATASET}/${id}.${extension}`
}
Querying the URL directly
However, if you can query for the file's document with GROQ that'd be easier:
*[(YOUR FILTER HERE)] {
file->{ url } // gets the URL from the referenced file
}
You can do the same with images, too.

Asp.Net Core - Not Able to Upload Files From Dropzone JS

I am using asp.net core 2.2 with dropzone js.
I am trying to submit a form along with the files contained in dropzone js.
I have an input file field (can be hidden or not hidden). I want to assign dropzone files to this field and submit it. But the Forms field is always null.
Here is the code:
MVC Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(ViewModels.Photo model)
{
var files = HttpContext.Request.Form.Files; // this is also empty
....
}
MVC Model:
public class Photo
{
...
public List<IFormFile> Files { get; set; }
}
HTML:
<form asp-action="Add" asp-controller="Photos" method="post" id="addForm" enctype="multipart/form-data">
<div class="dropzone">
<input asp-for="Files" type="file" multiple hidden/>
</div>
<button type="submit">Submit</button>
</form>
JS:
var e = "#addForm",
var t = new Dropzone(e, {
maxFilesize: 1,
acceptedFiles: ".png,.jpg,.jpeg",
uploadMultiple: false,
autoProcessQueue: false
});
t.on("addedfile", function (o) {
$("#Files").files = t.files;
})
You might use a different method signature of the action
[HttpPost]
public ActionResult Add(HttpPostedFileBase file)
{
//handle file.InputStream
}
This example shows uploading the files one by one: https://gillesleblanc.wordpress.com/2017/01/25/integrating-dropzone-js-into-an-asp-net-mvc-site/
I managed to get things working and it was a minor fix.
I changed below code
$("#Files").files = t.files;
to
$("#Files").files = t.hiddenFileInput.files;
t.files is an array of files being captured by dropzone where as t.hiddenFileInput.files is an FileList object of files being captured by dropzone.
The $("#Files").files is also an FileList object that's why t.files was not working due to type mismatch.
Now it submits form fields along with files with default submit mechanism.

unobtrusive validation not working with dynamic content

I'm having problems trying to get the unobtrusive jquery validation to work with a partial view that is loaded dynamically through an AJAX call.
I've been spending days trying to get this code to work with no luck.
Here's the View:
#model MvcApplication2.Models.test
#using (Html.BeginForm())
{
#Html.ValidationSummary(true);
<div id="res"></div>
<input id="submit" type="submit" value="submit" />
}
The Partial View:
#model MvcApplication2.Models.test
#Html.TextAreaFor(m => m.MyProperty);
#Html.ValidationMessageFor(m => m.MyProperty);
<script type="text/javascript" >
$.validator.unobtrusive.parse(document);
</script>
The Model:
public class test
{
[Required(ErrorMessage= "required field")]
public int MyProperty { get; set; }
}
The Controller:
public ActionResult GetView()
{
return PartialView("Test");
}
and finally, the javascript:
$(doument).ready(function () {
$.ajax({
url: '/test/getview',
success: function (res) {
$("#res").html(res);
$.validator.unobtrusive.parse($("#res"));
}
});
$("#submit").click(function () {
if ($("form").valid()) {
alert('valid');
return true;
} else {
alert('not valid');
return false;
}
});
The validation does not work. Even if I don't fill any information in the texbox, the submit event shows the alert ('valid').
However, if instead of loading dynamically the view, I use #Html.Partial("test", Model) to render the partial View in the main View (and I don't do the AJAX call), then the validation works just fine.
This is probably because if I load the content dynamically, the controls don't exist in the DOM yet. But I do a call to $.validator.unobtrusive.parse($("#res")); which should be enough to let the validator about the newly loaded controls...
Can anyone help ?
If you try to parse a form that is already parsed it won't update
What you could do when you add dynamic element to the form is either
You could remove the form's validation and re validate it like this:
var form = $(formSelector)
.removeData("validator") /* added by the raw jquery.validate plugin */
.removeData("unobtrusiveValidation"); /* added by the jquery unobtrusive plugin*/
$.validator.unobtrusive.parse(form);
Access the form's unobtrusiveValidation data using the jquery data method:
$(form).data('unobtrusiveValidation')
then access the rules collection and add the new elements attributes (which is somewhat complicated).
You can also check out this article on Applying unobtrusive jquery validation to dynamic content in ASP.Net MVC for a plugin used for adding dynamic elements to a form. This plugin uses the 2nd solution.
As an addition to Nadeem Khedr's answer....
If you've loaded a form in to your DOM dynamically and then call
jQuery.validator.unobtrusive.parse(form);
(with the extra bits mentioned) and are then going to submit that form using ajax remember to call
$(form).valid()
which returns true or false (and runs the actual validation) before you submit your form.
Surprisingly, when I viewed this question, the official ASP.NET docs still did not have any info about the unobtrusive parse() method or how to use it with dynamic content. I took the liberty of creating an issue at the docs repo (referencing #Nadeem's original answer) and submitting a pull request to fix it. This information is now visible in the client side validation section of the model validation topic.
add this to your _Layout.cshtml
$(function () {
//parsing the unobtrusive attributes when we get content via ajax
$(document).ajaxComplete(function () {
$.validator.unobtrusive.parse(document);
});
});
test this:
if ($.validator.unobtrusive != undefined) {
$.validator.unobtrusive.parse("form");
}
I got struck in the same problem and nothing worked except this:
$(document).ready(function () {
rebindvalidators();
});
function rebindvalidators() {
var $form = $("#id-of-form");
$form.unbind();
$form.data("validator", null);
$.validator.unobtrusive.parse($form);
$form.validate($form.data("unobtrusiveValidation").options);
}
and add
// Check if the form is valid
var $form = $(this.form);
if (!$form.valid())
return;
where you are trying to save the form.
I was saving the form through Ajax call.
Hope this will help someone.
just copy this code again in end of modal code
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
;)

How do you delete files before they have been uploaded by the dojo Multifile Uploader?

I am using a dojox.form.uploader.FileList here: https://github.com/chotchki/pgGallery/blob/master/src/main/webapp/WEB-INF/views/gallery/gallery.jsp#L129
I have looked through the API documentation and can't find a way to allow the user to remove a file from the list to be uploaded before they click upload.
Any ideas?
I found no solution too, so i wrote this little hack, it just extending dojox/form/Uploader. So far it seems to work for me, at least in Firefox. It adds a method removeFile(index) and a onRemove(file) method to the Uploader class.
What you need to do is use force="iframe" on your uploader Element or set the property on your object.
require(["dojo/_base/lang","dojox/form/Uploader","dojo/dom-construct","dojo/_base/array"],function(lang, Uploader, domConstruct, array){
lang.extend(Uploader,{
removeFile: function(index){
if(this._inputs.length > index){
//Delete input field from dom
domConstruct.destroy(this._inputs[index]);
//Delete file From input Array
var _arr = new Array();
var _file = this._inputs[index];
array.forEach(this._inputs,function(n,i){
if(i != index){
_arr.push(n);
}
});
this._inputs = _arr;
this.onRemove(_file);
}
},
onRemove: function(file){
}
});
});