How to upload a File with hibernate-ogm and Mongodb?

728 views Asked by At

I have been able to upload Strings and Dates into a Mongodb, but I cannot figure out how to get a file in there using a webapp.

I'd rather not use GridFS, but something like a byte[] or a blob (but if I must use GridFS, then, I must).

Here is what I have so far:

index.jsp:

<form action="./FileUploadServlet" method="POST">
    <input type="text" name="subject"/><br>
    <input type="date" name="docDate"/>
    <%--TODO: accept file into db--%>
    <input type="file" name="fileContent"/>

    <input type="submit" value="Submit">
</form>

FileUploadServlet.java:

//imports...

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/FileUploadServlet"})
public class FileUploadServlet extends HttpServlet {
         throws ServletException, IOException, Exception {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            FileUploadDAO fileUploadDAO = new FileUploadDAO();
            FileUploadEntity fileUploadEntity = new FileUploadEntity();
 String subject = request.getParameter("subject");
            String dateStr = request.getParameter("docDate");
            //TODO: GET FILE CONTENTS
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            fileUploadEntity.setSubject(subject);
            fileUploadEntity.setDocDate(date);
//TODO: SET FILE CONTENTS
            fileUploadDAO.persistAction(fileUploadEntity);
            response.sendRedirect("/jdc/index.jsp");
        } finally {
            out.close();
        }
    }
 @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (Exception ex) {
            Logger.getLogger(FileUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

How do I get the file in there? I tried

request.getParameter("fileContent");
request.getAttribute("fileContent");

but that did not work.

1

There are 1 answers

0
Jeff On

I was able to upload binary data into my database, but I'm not sure about how to retrieve it. Here is what I have though:

Add these lines to my processRequest method:

byte[] b = request.getParameter("fileContent").getBytes();


fileUploadEntity.setFileContent(b);