Thursday, February 15, 2018

Getting image/video from html into java servlet as new File()

Leave a Comment

I want to get a file (image or video) from an

<input type='file' id='file_i'/> // Not this <input type='submit'/> 

Using an XMLHttpRequest like this

function img() {             var fd = new FormData();             fd.append('file', document.getElementById("file_i").files[0]);             var req;             if (window.ActiveXObject) {                 req=new ActiveXObject();             } else {                 req=new XMLHttpRequest();             }             req.open("post", "Image", true);             req.send(fd);         } 

for example.
Then in the servlet doing this:

new FileInputStream(new File(request.getParameter("file"))) 

How can I retrieve that file? Thanks in advance.

2 Answers

Answers 1

I fixed it. Here it is:

JAVASCRIPT

var fd = new FormData(); fd.append('file', document.getElementById("file_i").files[0]); var req; if (window.ActiveXObject) {     req=new ActiveXObject(); } else {     req=new XMLHttpRequest(); } req.open("post", "Image", true); req.send(fd); 

JAVA

@MultipartConfig public class addImage extends HttpServlet {     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {         Part filePart = request.getPart("file");         InputStream fileContent = filePart.getInputStream(); } } 

XML

<servlet>         <servlet-name>Add Image</servlet-name>         <servlet-class>servlets.addImage</servlet-class> </servlet> <servlet-mapping>     <servlet-name>Add Image</servlet-name>     <url-pattern>/Image</url-pattern> </servlet-mapping> 

Answers 2

I think you miss some points.

  1. It seems in your JavaScript code, that you just create the request. But you didn't respond to results.

    req.addEventListener("load", reqListener); 

    You should define reqListener like that:

    function reqListener () {     // Here try to handle the response text, using "this.responseText"     console.log(this.responseText); } 

    See the full info here: Using XMLHttpRequest

  2. Also in your Java code, you just stated that you created a file stream. You should read from this input stream into the request's output stream. Also you should set the header Content-Type: put_your_mime_type_here, For example: Content-Type: application/json, if your file is a json file, Content-Type: image/png, if your file is a PNG image.

    See an example here: Example for making a file download URL in Java

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment