Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript to rename file before upload

Tags:

javascript

Let's say I have this list of forms like so:

var forms = document.getElementsByClassName('uploadImage');

each item in this list look like this:

<form method=​"post" action=​"/​upload" enctype=​"multipart/​form-data" id=​"f_x" class=​"uploadImage">

​    <input type=​"file" id=​"u_x">​
    <input type=​"submit" value=​"Submit" id=​"s_x">​

</form>​

where x = [0,1,2,3,4,5]

How do I loop through this list and do two things:

1 - Rename the file name

2 - Submit the form for uploading the file

I looked for many resources online like this one: https://www.telerik.com/forums/change-file's-name-when-it's-uploaded-via-html-form, all of them are using Jquery , I need it in javascript

update :-

I figured out how to get to the input value of each form

forms[0].elements[0] this will return the first input of the first form on the list

forms[0].elements[0].value this output the value of the file input

like image 494
LoopingDev Avatar asked Dec 12 '18 18:12

LoopingDev


People also ask

How do I rename a file while uploading?

We can change file name by using FileUpload control's SaveAs method. SaveAs() method require to pass a parameter named filename. This parameter value is a string that specifies the full path of the location of the server on which to save the uploaded file.

Can we upload file using JavaScript?

html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript. A pure JavaScript file uploader simplifies Ajax based interactions with the server.


1 Answers

So here is the code you linked to, and I will break it down a bit after. A lot of it is vanilla javascript.

$(document).ready(function() {

    initImageUpload();

    function initImageUpload() {
        $("#btn-submit").click(function(e) {
            e.preventDefault();

            var everlive = new Everlive({
                appId: "",
                scheme: "https"
            });

            // construct the form data and apply new file name
            var file = $('#image-file').get(0).files[0];

            var newFileName = file.filename + "new";
            var formData = new FormData();
            formData.append('file', file, newFileName);


            $.ajax({
                url: everlive.files.getUploadUrl(), // get the upload URL for the server
                success: function(fileData) {
                    alert('Created file with Id: ' + fileData.Result[0].Id); // access the result of the file upload for the created file
                    alert('The created file Uri is available at URL: ' + fileData.Result[0].Uri);
                },
                error: function(e) {
                    alert('error ' + e.message);
                },
                // Form data
                data: formData,
                type: 'POST',
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
        });
    }
});

As is mentioned, this uses jQuery $.ajax() to create an AJAX POST to the server with new FormData where the name of the file has been modified. The new FormData is then sent to the server instead of the HTML Form data.

So, when the button is clicked to submit the form, this event is prevented.

var file = $('#image-file').get(0).files[0];

This is then used to select the <input> element in jQuery and then collect the files info from the element.

var file = document.getElementById("image-file").files[0];

This can be done with JavaScript. Largely the rest of the script would be unchanged, except for the initialization and sending of POST Data via AJAX.

It might be best to create a function that you send the form to and it can then return the new form data with new name. As you did not want to provide an MCVE, it's hard to give you an example since it's not clear how the data for the new name would be create or gathered from.

function nameFile(inEl, newName){
  var file = inEl.files[0];
  var results = new FormData();
  results.append('file', file, newName);
  return results;
}

function sendFile(url, formData){
  var request = new XMLHttpRequest();
  request.open("POST", url);
  request.send(formData);
}

sendFile("/​upload", nameFile(document.getElementById("file-image"), "UserFile-" + new Date().now() + ".jpg"));

Another issue is if you have multiple forms, and multiple submit buttons, which one will trigger all the items to get uploaded? Either way, you'd have to iterate each form (maybe with a for() loop) collect the form data from each, update the name, and submit each one, most likely via AJAX.

Hope this helps.

like image 60
Twisty Avatar answered Oct 12 '22 23:10

Twisty