Skip to content Skip to sidebar Skip to footer

Upload File To Html Form, Rename It, And Return File To User

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

Solution 1:

Try this:

<html><head><title></title></head><body><inputid="uploadFile"type="file" /><inputtype="button"value="rename and download"onclick="initImageUpload()" /><aid="aDownload"></body><script>functioninitImageUpload() {
        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>

Solution 2:

try this

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

<inputtype="file"id="files"name="files"/><inputtype="text"id="newname"><button>rename</button><divid="output"></div><scriptsrc="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());
		});
		
		functionrenameFile(file, typeFile, newname) {
			var reader = newFileReader();
			reader.onload = function(event) {
				$('#output').append('<a href="data:'+ typeFile +';,'+ encodeURI(event.target.result) +'" download="'+newname+'">'+newname+'</a>');
			}
			reader.readAsBinaryString(file);
		}
	});
</script>

Post a Comment for "Upload File To Html Form, Rename It, And Return File To User"