Base solution for your next web application
Open Closed

Upload file with DropZone #3299


User avatar
1
20summers created

I have created document upload functionality.

I can create the record correctly, but wanted to add dropzone.js as the means by which I upload the document see image: [https://goo.gl/photos/ZSVgZCJrHDTBFnBC6])

The ideas is that you populate the Name and Category fields, then drag and drop a file. The file gets submited automatically and gets replaced with a DocumentId (once saved in the database), and then the user clicks save.

My Issue: my _createOrEditModal.js has the following code:

$(".dropzone").dropzone({
    url: "/App/Documents/UploadDocument/",
    uploadMultiple: false,
    paramName: "file",
    parallelUploads: 1,
    maxFiles: 1
});

I keep on getting a code 400 error when it tries to upload the file (it does not even go into the controller). I have spent a number of hours on this and cannot figure out whats going on.

Here is my controller code:

public ActionResult UploadDocument()
        {
            try
            {
                var documentFile = Request.Form.Files.First();

                //Check input
                if (documentFile == null)
                    throw new UserFriendlyException(L("File_Empty_Error"));

                byte[] fileBytes;
                using (var stream = documentFile.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                var documentFileObject = new BinaryObject(AbpSession.GetTenantId(), fileBytes);
                _binaryObjectManager.SaveAsync(documentFileObject);


                return Json(new AjaxResponse(new {id = documentFileObject.Id}));
            }
            catch (UserFriendlyException ex)
            {
                return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
            }
        }

7 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Can you check Logs.txt file under your web project for error details ? Probably you need to add anti forgery token to dropzone request.

    $(".dropzone").dropzone({
        url: "/App/Documents/UploadDocument/",
        uploadMultiple: false,
        paramName: "file",
        parallelUploads: 1,
        maxFiles: 1,
        headers:{
            "X-XSRF-TOKEN": abp.security.antiForgery.getToken()
        }
    });
    

    Thanks.

  • User Avatar
    0
    20summers created

    Awesome - Thanks - that was the trick :D

  • User Avatar
    0
    mdonogma created

    are you able to share a working sample of this - i'm new to ASPZero and trying to create an upload form with custom fields on same form,

  • User Avatar
    1
    20summers created

    Here is my code that I used...

    _createorEditModal has the following :

    <div class="row">
            <div class="col-md-12">
              
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <div class="panel-title">
                            Drag n' drop uploader
                        </div>
    
                    </div>
                    <form id="upload-widget" method="post" class="dropzone" enctype="multipart/form-data" required>
                    </form>
                    
                </div>
              
            </div>
        </div>
    

    _CreateOrEditModal.js has the following: you will see it returns the saved documents Id

    $(document).ready(function () {
        Dropzone.autoDiscover = false;
        $(".dropzone").dropzone({
            url: "/App/Documents/UploadDocument/",
            uploadMultiple: false,
            paramName: "file",
            parallelUploads: 1,
            maxFiles: 1,
            headers: {
                "X-XSRF-TOKEN": abp.security.antiForgery.getToken()
            },
            success: function (file, response) {
                $('#form').append('<input type="hidden" name="DocumentId" value="' + response.result.id + '" />');
            }
        });
    });
    

    the Document controller:

    [HttpPost]
           [AllowAnonymous]
            public ActionResult UploadDocument()
            {
                try
                {
                    var documentFile = Request.Form.Files.First();
    
                    string ext = Path.GetExtension(documentFile.FileName);
    
                    //Check input
                    if (documentFile == null)
                        throw new UserFriendlyException(L("File_Empty_Error"));
    
                    byte[] fileBytes;
                    using (var stream = documentFile.OpenReadStream())
                    {
                        fileBytes = stream.GetAllBytes();
                    }
    
                    var documentFileObject = new BinaryObject(AbpSession.GetTenantId(), fileBytes);
                    _binaryObjectManager.SaveAsync(documentFileObject);
    
                    
    
                    return Json(new AjaxResponse(new {id = documentFileObject.Id }));
                }
                catch (UserFriendlyException ex)
                {
                    return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
                }
            }
    
  • User Avatar
    0
    mdonogma created

    rock star ! thank you so much for this.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Thanks @20summers :)

  • User Avatar
    0
    AstarIT created

    That works very well, Now what about ot save the files in a folder intead the database? any idea will be grantly appreciated. Thnak you