如何使用Java Webapp将文件上传到MongoDB?

时间:2013-08-20 20:43:43

标签: java mongodb spring-mvc file-upload spring-data-mongodb

我正在尝试编写一个简单的WebApp来将文件上传到MongoDB数据库。我能够上传文档的主题和对象的日期(作为字符串数据类型)。我现在正在尝试将实际文件上传到MongoDB中并且证明是困难的。我尝试了MultipartFile,但它不会加载文件。然后我尝试将字符串添加到文件路径并产生Null Pointer异常(可能是因为字符串路径是本地资源,而不是服务器上的。)

如何使用webapp将文件上传到MongoDB?我为所有代码道歉,但我不知道应该发布多少。

错误:

java.lang.NullPointerException
at java.io.File.<init>(File.java:251)
at com.jcdc.domain.FileUpload.setFile(FileUpload.java:34)
at com.jcdc.controller.DocumentController.create(DocumentController.java:43)
at com.jcdc.controller.DocumentController$$FastClassByCGLIB$$f5f3eaff.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.jcdc.controller.DocumentController$$EnhancerByCGLIB$$6b66bfcf.create(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

以下是我的文件:

域名图层

FileUpload.java

package com.jcdc.domain;

import org.springframework.data.annotation.Id;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@org.springframework.data.mongodb.core.mapping.Document
public class FileUpload {
    @Id
    private String id;
    MultipartFile file;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(String filePath) {
        File f = new File(filePath);
        this.file = (MultipartFile) f;
    }
}

Document.java

package com.jcdc.domain;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;

@org.springframework.data.mongodb.core.mapping.Document
public class Document  {

    @Id
    private String id;

    private String subject;
    private String date;


    @DBRef
    private FileUpload file;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public FileUpload getFile() {
        return file;
    }

    public void setFile(FileUpload file) {
        this.file = file;
    }
}

控制器层

DocumentController.java

package com.jcdc.controller;

import com.jcdc.domain.Document;
import com.jcdc.domain.FileUpload;
import com.jcdc.dto.DocumentListDto;
import com.jcdc.service.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/documents")
public class DocumentController {

    @Autowired
    private DocumentService service;

    @RequestMapping
    public String getDocumentsPage() {
        return "documents";
    }

    //...

    @RequestMapping(value="/create", method=RequestMethod.POST)
    public @ResponseBody Document create(
            @RequestParam String subject,
            @RequestParam String date, String filepath) {

        FileUpload newFile = new FileUpload();
        newFile.setFile(filepath);
        System.out.println(filepath);
        System.out.println(newFile.getFile().toString());

        Document newDocument = new Document();
        newDocument.setFile(newFile);
        newDocument.setSubject(subject);
        newDocument.setDate(date);

        return service.create(newDocument);
    }
}

查看图层

document.jsp

<div id='newForm'>
        <form>
            <fieldset>
                <legend>Create New Record</legend>
                <label for='newSubject'>Subject</label><input type='text' id='newSubject'/><br/>
                <label for='newDate'>Date</label><input type='date' id='newDate'/><br/>
                <label for='newFile'>File</label><input type='file' id='newFile'/><br/>
            </fieldset>
            <input type='button' value='Close' id='closeNewForm' />
            <input type='submit' value='Submit'/>
        </form>

custom.js

function submitNewRecord() {
        $.post(urlHolder.add, {
            subject: $('#newSubject').val(),
            date: $('#newDate').val(),
            file: $('#newFile').val()
        }, 
        function(response) {
            if (response != null) {
                loadTable();
                toggleForms('hide');
                toggleCrudButtons('show');
                alert('Success! Record has been added.');
            } else {
                alert('Failure! An error has occurred!');
            }
        }
    );  
}

1 个答案:

答案 0 :(得分:4)

您可以使用Spring Data将org.springframework.data.mongodb.gridfs.GridFsOperations注入到MongoDB中的存储文件中。如果您不想使用Spring Data,则MongoDB的Java驱动程序提供com.mongodb.gridfs.GridFS。事实上,GridFsTemplete的实施GridFsOperations使用了GridFS。请参阅使用的链接示例。