简体   繁体   中英

How do I make a JSP page to upload an image to a MySQL database?

I have a web project written in JSP with a couple of Java classes for the back-end. I want to make a page where the user uploads an image and this gets saved in a database.

I have a page where the user uploads the image, with a form like this:

<form action="UploadImage.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*">
<input type="submit" name="submit" value="Upload Image">

I want to have my UploadImage.jsp file save this image to a LongBLOB object in a MySQL database. I tried using request.getParameter(), and request.getPart(), but they both return null, and any attempts to use these results in a NullPointerException.

I've tried looking online, but all the solutions involve using a servlet, instead of a JSP page. And yes, I know using JSP is not best practice, but for the purposes of this project, it's what I have to use.

You can use the ServletFileUpload class to parse the request and upload multiple files, in your case the image, to a temp directory on the server and then you'll just need to store the file's location as a path in the database.

ServletContext context = pageContext.getServletContext();    
String filePath = "c:\\apache-tomcat\\webapps\\images\\";

DiskFileItemFactory factory = new DiskFileItemFactory();      
factory.setRepository(new File("c:\\temp"));
ServletFileUpload uploader = new ServletFileUpload(factory);

try { 
    List files = upload.parseRequest(request);
    Iterator<FileItem> iter = fileItems.iterator();

    while (iter.hasNext()) {
        FileItem file = iter.next();            
        File serverFile = new File(filePath + 
            file.getName().substring(fileName.lastIndexOf("\\")));            
        file.write(serverFile);
    }
} catch(Exception ex) {
    System.out.println(ex);
}

You have to use the

Part p=request.getpart("file");

inputstream is=p.getinputstream(p);

byte[] b=Ioutils.getBytes(is);

Then You can use Setbytes to stored in mysql

And you also declared the multipart annotations on your servlet before class name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM