1

I'd like to know how can I upload an input file to my database (MySQL) with just JavaScript (using JSP). I've been searching for days & I haven't got luck.

All I do is: grab the inputs' values with 'getElementById' from the HTML code, then I send them to a JSP which it catches them with 'request.getParameter' & put them into their SETS so they can be uploaded into the database. All I want is upload a file (pic, xls, doc or PDF).

(with .value, it shows me: "C:/fakepath/file.jpg" [Browsers' Security rules]. How can I get the file's value & send it to the JSP where I put it into its SETS & then upload it?).

Well, my HTML looks like:

<table>
  <tr>
    <td>
      Name: <input type="text" name="yourName" id="yourName" />
    </td>
  </tr>
  <tr>
    <td>
      Photo: <input type="file" name="yourFile" id="yourFile" />
    </td>
  </tr>
  <tr>
    <td>
      <button type="button" onClick="Save()">Save</button>
    </td>
  </tr>
</table>

My JavaScript looks like this:

function nuevoAjax() {
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;
}


function Save(){
  ajax = nuevoAjax();
  
  var name = document.getElementById("yourName").value;
  var photo = document.getElementById("yourFile").value; //.value(?)
  
  ajax.open("POST", "saveData.jsp?name="+name+"&photo="+photo, true);
  ajax.onreadystatechange = function () {
     if (ajax.readyState == 4) {
         alert(ajax.responseText);
     }
  }
  ajax.send();
}

& my saveDate.jsp looks like:

<%
  String name = request.getParameter("name");
  XXXXX photo = request.getParameter("photo");

  objUser.setName(name);
  objUser.setPhoto(photo);
  
  objUser.saveUser(); // This method has: INSERT INTO & returns Msg (Uploaded / Error)
  
  out.print(objUser.getMsg());
%>

I've been breaking my back trying' to find something that helps me with this for days. Thanks in advance!

  • Any reason to use JSP instead of Servlets? – seenukarthi Aug 10 '15 at 16:54
  • If you can use [_FormData_](https://developer.mozilla.org/en-US/docs/Web/API/FormData), use that. Otherwise you have to send `input.files[0]` directly. In either instance you pass this in the first arg of `xhr.send` – Paul S. Aug 10 '15 at 16:56
  • I searched about FormData but I didn't get luck (using .value). I tried with .files[0] & it returns an [Object file], but how can I catch it with my JSP. I mean: "XXXX.parseXXX(request.getParameter("file"));". – JairKaulitz89 Aug 10 '15 at 17:17
  • Maybe this would help: http://stackoverflow.com/questions/6211145/upload-file-with-ajax-xmlhttprequest – glw Aug 10 '15 at 20:00
  • I found this: www.technicaladvices.com/2011/12/10/ajax-file-upload-to-a-java-servlet-in-html5/ & it worked out (Hope this helps someone else). Thanks anyway. – JairKaulitz89 Aug 13 '15 at 15:58

0 Answers0