4

MongoDB データベースにファイルをアップロードする単純な WebApp を作成しようとしています。ドキュメントの件名とオブジェクトの日付を (文字列データ型として) アップロードできます。現在、実際のファイルを MongoDB にアップロードしようとしていますが、難しいことがわかっています。MultipartFile を試しましたが、ファイルが読み込まれませんでした。次に、文字列をファイル パスに取得しようとしたところ、Null Pointer 例外が発生しました (おそらく、文字列パスがサーバー上ではなくローカル リソースにあるためです)。

Web アプリケーションを使用して 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;
    }
}

ドキュメント.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);
    }
}

レイヤーを表示

ドキュメント.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!');
            }
        }
    );  
}
4

1 に答える 1

6

You can inject org.springframework.data.mongodb.gridfs.GridFsOperations to store file in MongoDB with Spring Data. If you don't want use Spring Data then Java driver for MongoDB provides com.mongodb.gridfs.GridFS. In fact GridFsTemplete which is implementation of GridFsOperations uses GridFS under the hood. See linked examples of useage.

于 2013-08-20T22:47:29.390 に答える