JERSEY 2.0 - Multipart @FormDataParam问题

时间:2014-08-02 04:01:43

标签: java mysql sql rest jersey

在我提出问题之前,先了解一下Web服务。我正在为当地学校建立一项服务,让学生上传讲义以便在开放平台上分享。

首先,我在本地计算机上运行了一个MySQL实例。我的Web服务REST JERSEY 2.0连接到我的数据库,可以查询它。我有一个HTML页面,我可以在文本字段中键入要搜索的参数,它会命中存储过程并按预期返回结果。

我有另一个存储过程接受输入参数作为表单的一部分,并将新记录插入到我的数据库中。这也可以成功。

我现在想要发生的事情是,在我将新记录插入我的数据库之前,我想将文件上传到某个位置,然后在成功上传之后,将数据插入数据库中。

我有一个HTML表单设置,所有文件都发布在下面。我无法实现我需要的多部分东西。我在网上找到的所有示例和教程都没有多大帮助。我不确定这个版本的JERSEY中罐子中的文件位置是否发生了变化,或者我从其他任何人身上看到的东西都没有为我工作。

以下是错误代码:

WARNING: No injection source found for a parameter of type public static void com.dylanlegendre.dbhelper.FilePaths.uploadNewFile(java.io.InputStream,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) at index 0.

Aug 01, 2014 10:34:01 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public static void com.dylanlegendre.dbhelper.FilePaths.uploadNewFile(java.io.InputStream,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) at index 0.; source='ResourceMethod{httpMethod=POST, consumedTypes=[application/x-www-form-urlencoded], producedTypes=[text/html], suspended=false, suspendTimeout=0, suspendTimeoutUnit=MILLISECONDS, invocable=Invocable{handler=ClassBasedMethodHandler{handlerClass=class com.dylanlegendre.dbhelper.FilePaths, handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@64114e1a]}, definitionMethod=public static void com.dylanlegendre.dbhelper.FilePaths.uploadNewFile(java.io.InputStream,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String), parameters=[Parameter [type=class java.io.InputStream, source=file, defaultValue=null], Parameter [type=class java.lang.String, source=file, defaultValue=null], Parameter [type=class java.lang.String, source=filename, defaultValue=null], Parameter [type=class java.lang.String, source=filedate, defaultValue=null], Parameter [type=class java.lang.String, source=filetype, defaultValue=null], Parameter [type=class java.lang.String, source=teacherfirst, defaultValue=null], Parameter [type=class java.lang.String, source=teacherlast, defaultValue=null], Parameter [type=class java.lang.String, source=bookisbn, defaultValue=null], Parameter [type=class java.lang.String, source=bookauthorfirst, defaultValue=null], Parameter [type=class java.lang.String, source=bookauthorlast, defaultValue=null], Parameter [type=class java.lang.String, source=userid, defaultValue=null], Parameter [type=class java.lang.String, source=classname, defaultValue=null], Parameter [type=class java.lang.String, source=classsection, defaultValue=null], Parameter [type=class java.lang.String, source=schoolname, defaultValue=null], Parameter [type=class java.lang.String, source=schoolstate, defaultValue=null], Parameter [type=class java.lang.String, source=schoolzip, defaultValue=null], Parameter [type=class java.lang.String, source=fileurl, defaultValue=null]], responseType=void}, nameBindings=[]}']
at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:465)
at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:163)
at org.glassfish.jersey.server.ApplicationHandler$3.run(ApplicationHandler.java:323)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:289)
at org.glassfish.jersey.internal.Errors$2.call(Errors.java:286)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:286)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:320)
at org.glassfish.jersey.server.ApplicationHandler.<init>(ApplicationHandler.java:285)
at org.glassfish.jersey.servlet.WebComponent.<init>(WebComponent.java:310)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:169)
at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:359)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
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:744)

我的休息班:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;

@Path("/getfilepaths")
public class FilePaths extends Application {

    /**
     * Queries the database by filename and order by date desc
     * 
     * @param filename
     * @return
     */

    @Path("/filename")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public static String getFilePathByName(@QueryParam("filename") String filename) {
        ResultSet rs = null;
        String result = "";
        String query = "CALL usp_NP_GetFilesByName('" + filename + "');";

        DBHelper myDB = new DBHelper();
        myDB.openConnection();

        rs = myDB.ExecuteQuery(query);

        ArrayList<String> name = new ArrayList<String>();
        ArrayList<String> date = new ArrayList<String>();
        ArrayList<String> path = new ArrayList<String>();

        try {
            while(rs.next()){
               name.add(rs.getString("FileName"));
               date.add(rs.getString("FileDate"));
               path.add(rs.getString("FilePath"));
            }
        } catch (SQLException e) {

            e.printStackTrace();
        }

        result = "  FILENAME    ...      FILEDATE      ...       FILEPATH             \n";


        for(int counter = 0; counter <= name.size() - 1; counter++) {
            result = result + name.get(counter) + " ... " + date.get(counter) + " ... " + path.get(counter) + "\n";
        }

        myDB.closeConnection();

        return result;
    }

    /**
     * INSERT a new record in tbluploadedfiles after uploading a new file
     * 
     * @param filename
     * @param filedate
     * @param filetype
     * @param teacherfirst
     * @param teacherlast
     * @param bookisbn
     * @param bookauthorfirst
     * @param bookauthorlast
     * @param userid
     * @param classname
     * @param classsection
     * @param schoolname
     * @param schoolstate
     * @param schoolzip
     * @param fileurl
     * @throws Exception 
     */

    @Path("/INSERT")
    @POST 
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    //@Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces({MediaType.TEXT_HTML})    
    public static void uploadNewFile(
                        @FormParam("file") InputStream uploadedInputStream,
                        @FormParam("file") String file, //the name of the file we uploaded literally
                        @FormParam("filename") String filename, //the name the user chooses for new file storage
                        @FormParam("filedate") String filedate,
                        @FormParam("filetype") String filetype,
                        @FormParam("teacherfirst") String teacherfirst,
                        @FormParam("teacherlast") String teacherlast,
                        @FormParam("bookisbn") String bookisbn,
                        @FormParam("bookauthorfirst") String bookauthorfirst,
                        @FormParam("bookauthorlast") String bookauthorlast,
                        @FormParam("userid") String userid,
                        @FormParam("classname") String classname,
                        @FormParam("classsection") String classsection,
                        @FormParam("schoolname") String schoolname,
                        @FormParam("schoolstate") String schoolstate,
                        @FormParam("schoolzip") String schoolzip,
                        @FormParam("fileurl") String fileurl
                        )  {

        boolean wasSuccessful = false;

        //process uploaded file first to server

        if (file != null && !wasSuccessful) {

            String uploadedFileLocation = "C://uploaded/";

            // save it
            writeToFile(uploadedInputStream, uploadedFileLocation);

            wasSuccessful = true;

        } else
            try {
                throw new Exception("You must select a file to upload");
            } catch (Exception e) {
                e.printStackTrace();
            }


        //insert new record of processed file into tbluploadedfiles if upload successful

        if (wasSuccessful) {

        fileurl = filename + filetype + filedate + userid + schoolzip + classsection + file;

        UploadedFile x = new UploadedFile(filename, filedate, filetype, teacherfirst, teacherlast, bookisbn, bookauthorfirst, bookauthorlast,
                                        userid, classname, classsection, schoolname, schoolstate, schoolzip, fileurl);

        String query = "CALL usp_NP_InsertFile('" + x.getFileName() + "', '" + x.getFileDate() + "', '" + x.getFileType() + "', '" + x.getTeacherFirst() + "', '" + x.getTeacherLast() + "', '" + x.getBookISBN() + "', '" + x.getBookAuthorFirst() + "', '" + x.getBookAuthorLast() + "', '" + x.getUserID() + "', '" + x.getClassName() + "', '" + x.getClassSection() + "', '" + x.getSchoolName() + "', '" + x.getSchoolState() + "', '" + x.getSchoolZip() + "', '" + x.getFileURL() + "');";

        DBHelper myDB = new DBHelper();
        myDB.openConnection();

        myDB.ExecuteQuery(query);

        myDB.closeConnection();

        } else
            try {
                throw new Exception("An error has occured when uploading the file");
            } catch (Exception e) {
                e.printStackTrace();
            }


    }

    /**
     * save uploaded file to new location
     * 
     * @param uploadedInputStream
     * @param uploadedFileLocation
     */
    private static void writeToFile(InputStream uploadedInputStream,
            String uploadedFileLocation) {

        try {
            OutputStream out = new FileOutputStream(new File(
                    uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }



}

我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>notepal_v1_ws</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>com.dylanlegendre.dbhelper</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

我的HTML文件用于测试:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-Equiv="Cache-Control" Content="no-cache">
<meta http-Equiv="Pragma" Content="no-cache">
<meta http-Equiv="Expires" Content="0">

<title>Development Environment</title>

<script>

//query the database by file name
function queryDatabase() {

    var url = "http://localhost:8080/notepal_v1_ws/rest/getfilepaths/filename?filename=";
    var strSearch = document.getElementById('txtSearch').value;

    var query = url + strSearch;

    var win = window.open(query, '_blank');
    win.focus();
}


//get date
function grabDate() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; 
    var yyyy = today.getFullYear();

    if(dd<10) {
        dd='0'+dd
    } 

    if(mm<10) {
        mm='0'+mm
    } 

    today = yyyy + '-' + mm + '-' + dd;

    document.getElementById("txtFileDate").value=today;

    return today;
}

</script>

</head>

<body>

<h1>dev</h1>

<br /><br />

Query the database by searching for a filename.
<br />
<input name="txtSearch" id="txtSearch" type="text" dir="ltr" size="25" maxlength="25" />
<input name="btnSubmitQuery" id="btnSubmitQuery" value="Search" type="button" onClick="queryDatabase()" />

<br /><br />

<h3>Upload A File</h3>
<br />
<font color="red">*</font> designates required fields.
<br />
<br />

<form action="http://localhost:8080/notepal_v1_ws/rest/getfilepaths/INSERT?" method="post" enctype="multipart/form-data">

<br />
<font color="red">*</font>Select a file to upload (.docx, .txt, .pdf, etc.)
<br />
<input name="file" id="file" type="file" size="50" />
<br />

<font color="red">*</font>Choose a meaningful name for the file, EXAMPLE: Chapter 10 Notes
<br/ >
<input name="filename" id="txtFileName" type="text" dir="ltr" size="25" maxlength="25" />
<br />
Date (auto date; leave as is)
<br />
<input name="filedate" id="txtFileDate" type="text" dir="ltr" size="25" maxlength="25" onfocus="grabDate()" />
<br />
<font color="red">*</font>Choose a FileType
<br/ >
<select name="filetype" id="txtFileType" size="5">
  <option value="Homework">Homework</option>
  <option value="Test">Test</option>
  <option value="Quiz">Quiz</option>
  <option value="Notes">Notes</option>
  <option value="StudyGuide">Study Guide</option>
</select>
<br />
Teacher First Name
<br/ >
<input name="teacherfirst" id="txtTeacherFirst" type="text" dir="ltr" size="25" maxlength="25" />
<br />
Teacher Last Name
<br/ >
<input name="teacherlast" id="txtTeacherLast" type="text" dir="ltr" size="25" maxlength="25" />
<br />
Book ISBN, EXAMPLE: 191827-BFHS1283
<br/ >
<input name="bookisbn" id="txtBookISBN" type="text" dir="ltr" size="25" maxlength="25" />
<br />
Book Author First Name
<br/ >
<input name="bookauthorfirst" id="txtBookAuthorFirst" type="text" dir="ltr" size="25" maxlength="25" />
<br />
Book Author Last Name
<br/ >
<input name="bookauthorlast" id="txtBookAuthorLast" type="text" dir="ltr" size="25" maxlength="25" />
<br />
UserID (auto entered; leave blank)
<br />
<input name="userid" id="txtUserID" type="text" dir="ltr" size="25" maxlength="25" value="1" />
<br />
Class Name, EXAMPLE: Calculus II
<br/ >
<input name="classname" id="txtClassName" type="text" dir="ltr" size="25" maxlength="25" />
<br />
Class Section, EXAMPLE: 205
<br/ >
<input name="classsection" id="txtClassSection" type="text" dir="ltr" size="25" maxlength="25" />
<br />
School/University Name, 
<br/ >
<input name="schoolname" id="txtSchoolName" type="text" dir="ltr" size="25" maxlength="25" />
<br />
School State Code, 
<br/ >
<input name="schoolstate" id="txtSchoolState" type="text" dir="ltr" size="25" maxlength="25" />
<br />
School Zip Code,
<br/ >
<input name="schoolzip" id="txtSchoolZip" type="text" dir="ltr" size="25" maxlength="25" />
<br />
FileURL (auto entered; leave blank)
<br />
<input name="userid" id="txtUserID" type="text" dir="ltr" size="25" maxlength="25" value="TEST.docx" />

<br /><br />
<input type="submit" value="Upload"/>
</form>


</body>
</html>

0 个答案:

没有答案