Specify Name for Uploaded File At Upload Time Using DropZone.js



Background:
After surmounting my last challenge with dropzone.js and was able to upload my files. I was immediately faced with another one. The dropzone.js implementation apparently doesn't include any method for computing a value to send to the server while the file is being uploaded. What this means is that any headers or form data used to initialize the dropzone will be used repeatedly each time a file is uploaded.

Issue:
This meant that, for instance if I didn't want to upload a file using its name from the client, I may not be able to specify another name for the file as it is being uploaded. And that was exactly what I was faced with. Each time I created another record and uploaded a corresponding file with the dropzone, the file would overwrite my previous files, because I was apparently sending the same custom filename to the server to save my files with. My dropzone initialization code looked like this
var mydropzone = $(targetelement).dropzone({
            url: 'uploading_page.aspx', headers: { "folderpath": folderPathOnServer },

           sending: function (file, xhr, formData) {
                filenameOnServer = $.session.get('userid') + '_' + (new Date()).getTime();
                formData.append("MyRealName", filenameOnServer);
            }, success: function (file, response) {

                  $(targetelement).attr("src", PictureRoot + folderRightPart + filenameOnServer;
            }
         });

Take note of the variable filenameOnServer. My intent was to notify the server of the new filename each time I uploaded a file with this variable. The fact that I appended (new Date()).getTime() already gives away my expectation that this should be a unique value each time the upload was done using the drag-drop. Unfortunately, dropzone.js doesn't work that way. The plugin computes the filenameOnServer at initialization and uses the same value throughout every upload.

I didnt want to tweak the plugin, so after reading through the entire documentation and ransacking the web with google's help to no avail, I had to implement a workaround, which is actually a simple one.

Solution:
The unique file name should be generated on the server. And made available to the client in the Response. With PHP, use echo json_encode($result), and in ASP.Net C# use Response.Write("result");

Notice that the success method in your dropzone initialization has two parameters; file and response. The response parameter will contain the response provided by the server (in my own case, it was the filename computed at the server) which you can work with.

Simple right?

Comments

Popular posts from this blog

Resize or Crop Image before Upload Using HTML5 File API

Get Creative With Data Tables: Row Click Events

Exception from HRESULT: 0x80131040