0

I am trying to upload a file to server using JavaScript as dynamically generating a form along with input file while clicking a button.

But here, uploading File is not appending to form tag inside the script, so that upload function not works.

My code in html file as follows,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
    <div id="formActive">
        <button onclick="imageContent();">click</button>
    </div>
<script>
function imageContent(){
    var imgContent = "file";
    var fileContent = document.createElement('input');
    fileContent.name = 'file';
    fileContent.type = 'hidden';
    var lastImageFile = "imageName";
    var boundary=Math.random().toString().substr(2);
    multipart = "--" + boundary
                   + "\r\nContent-Disposition: form-data; name=" + lastImageFile
                   + "\r\nContent-type: application/octet-stream"
                   + "\r\n\r\n" + imgContent + "\r\n";
    multipart += "--"+boundary+"--\r\n";

    fileContent.value = imgContent;

    var form = document.createElement('form');
    form.method = "POST";
    form.action = "mydomain.com/upload";
    form.enctype = "multipart/form-data";
    form.appendChild(fileContent);
    document.getElementById("formActive").appendChild(form);
    form.submit();
}
</script>
</body>
</html>

While looking into the upload servlet, I didn't get any file name in request.

Can anyone assist that where I did mistake?

DevGo
  • 907
  • 1
  • 12
  • 38

0 Answers0