2

I have a file (data) that I send to a servlet using a XMLHtppRequest JS object. I have no problems with this. I receive it by request.getInputStream() in the servlet, parse it and get the file perfectly. The problems come when I also have to send/receive the name of the file. I'm trying to put that file name inside of an <input type="hidden"> and send it calling submit() method in javascript. The point is that I cant' get it using request.getParameter("fileName"); (it's always null) from the servlet and I don't know if I'm doing something wrong or I just can't have a submit() plus an XMLHtmlRequest.send() together (two POSTs).

Javascript:

function save(data){

    var loadedFilename = "exampleFileName";
    var xhr = new XMLHttpRequest();
    var base64data = (new core.Base64()).convertUTF8ArrayToBase64(data);

    xhr.open("POST", "ServletUpload", true);
    xhr.send(base64data);

    document.getElementById("fileName").value = loadedFilename;
    document.forms["formExample"].submit();
}

Servlet doPost method:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub

    String fileName = request.getParameter("fileName");

    byte[] content = Base64.decodeBase64(IOUtils.toByteArray(request.getInputStream()));

    ByteArrayInputStream input = new ByteArrayInputStream(content);

    FileOutputStream file = new FileOutputStream("/home/user/Documents/workspace/tests/editingTests.odt");
    IOUtils.copy(input, file);

    input.close();
    file.close();
}

HTML form:

<form method="POST" name="formExample" action="ServletUpload">
    <input type="hidden" name="fileName" id="fileName" />
</form>
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Drumnbass
  • 867
  • 1
  • 14
  • 35
  • Since the form is having Method attribute set to - "POST", you will not get a request "parameter"(parameter appended to URL) with name fileName on server side. Try `request.getAttribute()` instead. – ring bearer May 11 '15 at 09:23
  • @ringbearer, unfortunately that doesn't work, it's still null. Anyway, I've used before getParameter() with POST method without any problems. – Drumnbass May 11 '15 at 10:01
  • See this http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest – ring bearer May 11 '15 at 10:07

1 Answers1

1
function save(data){

    var loadedFilename = "exampleFileName";
    var xhr = new XMLHttpRequest();
    var base64data = (new core.Base64()).convertUTF8ArrayToBase64(data);

    //changing this line should fix the problem 
    xhr.open("POST", "ServletUpload"+"?fileName="+loadedFilename , true);
    xhr.send(base64data);

    //following two lines are not needed 
    //document.getElementById("fileName").value = loadedFilename;
    //document.forms["formExample"].submit();
}
DoubleMa
  • 368
  • 1
  • 8
xerius
  • 94
  • 8