Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 572
MBJH Avatar asked Feb 06 '18 19:02

MBJH


1 Answers

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>
like image 106
MBJH Avatar answered Oct 05 '22 22:10

MBJH