Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery File Upload, only single image and rename before uploading

I am using the JQuery File Upload plugin.

I want to limit upload to one image, and replace if another image is selected, and rename before uploading to the server.My html code

<span class="btn btn-success fileinput-button">
    <i class="glyphicon glyphicon-plus"></i>
    <span>Add files...</span>
    <input id="fileupload" type="file" name="files[]"> 
</span>

I tried to make few changes in file

jquery.fileupload.js

but no success.

like image 333
Fahad Khan Avatar asked Oct 03 '22 00:10

Fahad Khan


2 Answers

I realize this was asked a long time ago, but the other response is an incomplete answer when other tools like DropzoneJS have a way to alter the filename before it is sent to the server. After scouring the source code, it turns out that jQuery File Upload also has the ability.

In a jQuery File Upload submit event callback OR at any time before calling data.submit(), alter the files array and set uploadName. For example:

$('#fileupload').fileupload({
    maxNumberOfFiles: 1,
    submit: function(e, data) {
        data.files[0].uploadName = 'mynewfilename.jpg';
    }
});

While the name property on a browser-controlled File object is read-only, that doesn't stop new properties from being defined. jQuery File Upload sends uploadName if it exists, otherwise it falls back to name.

Of course, nothing here excludes server-side responsibilities to validate the incoming data, but it does show that it is possible to change the filename that jQuery File Upload sends to the server.

like image 161
CubicleSoft Avatar answered Oct 13 '22 10:10

CubicleSoft


For security reasons client side javascripts do not have control of this. You can rename the file on the server when it gets uploaded.

Similar question and answer ware given here rename file that user uploads javascript

Best practice is to rename files on server-side, e.g. in the PHP script

you can limit your files with maxNumberOfFiles option

$('#fileuploadbasic').fileupload({
    maxNumberOfFiles: 1
});
like image 24
sulest Avatar answered Oct 13 '22 12:10

sulest