-1

Looking to build a little JavaScript web tool to rename files without needing to send them to a server. Ideally, I'd like to upload a file to a form, to either input type="file" or DataTransfer (drag/drop), then run a script to change the file.name, then present the renamed file to the user, all client side.

Is this possible? I know how to rename the files, but how to let the user save the new file without sending it to a server?

Thanks!

Jesse
  • 508
  • 5
  • 12
  • It's possible, you'd have to [read the file into the browser](https://stackoverflow.com/questions/4950567/reading-client-side-text-file-using-javascript) and then [create a link to the renamed file](https://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to-download-not-through-server) – James Jan 25 '18 at 22:18

2 Answers2

0

Try this:

<html>
<head>
    <title></title>
</head>
<body>
    <input id="uploadFile" type="file" />
    <input type="button" value="rename and download" onclick="initImageUpload()" />
    <a id="aDownload">
</body>
<script>
    function initImageUpload() {
        var file = uploadFile.files[0];
        var a = document.getElementById('aDownload');
        a.href = file.name;

        var ext = file.name.split('.').pop();
        var filename = file.name.substring(0, file.name.lastIndexOf('.'));

        var newFileName = filename + "new" + "." + ext;//provide the new name here

        a.setAttribute("download", newFileName);
        a.click();
    }
</script>
</html>
Vahid Farahmandian
  • 6,081
  • 7
  • 42
  • 62
0

try this

if you want multiple or drag and drop, just edit it

<input type="file" id="files" name="files"/>
<input type="text" id="newname"> <button>rename</button>
<div id="output"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(function(){
  $('button').click(function(){
   renameFile($('#files')[0].files[0], a.files.type, $('#newname').val());
  });
  
  function renameFile(file, typeFile, newname) {
   var reader = new FileReader();
   reader.onload = function(event) {
    $('#output').append('<a href="data:'+ typeFile +';,'+ encodeURI(event.target.result) +'" download="'+newname+'">'+newname+'</a>');
   }
   reader.readAsBinaryString(file);
  }
 });
</script>
plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31