首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >哪个JAR包含getPart()方法?

问哪个JAR包含getPart()方法?
EN

Stack Overflow用户
提问于 2014-02-20 18:09:50
回答 1查看 1.1K关注 0票数 1

我正在尝试从Apache7.0服务器上传一个文件到mySQL数据库。我已经编写了上传文件的html代码。

代码语言:javascript
复制
<form action="UploadValidate.jsp" method="post" enctype="multipart/form-data">
    <fieldset>
    <legend><font size="4" color="white">File Upload</font></legend><br/><br/>
    <font size="4" color="white"><b>
    <h3> Select File to Upload</h3> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
    <input type="file"name="file" /><br/><br/>

    <center>
    <input type="submit" value="Upload File" /><br/><br/></center>

    </font>
    </fieldset>
</form>

这是UploadValidate.jsp

代码语言:javascript
复制
      <%@ page import="java.io.*,java.sql.*,java.lang.String.*,com.oreilly.servlet.*"%>
      <%
       InputStream inputstream=null;
       String str=request.getParameter("file");
       Part filePart=request.getPart(str);
       out.println(filePart);
       if(filePart!=null){
           out.println(filePart.getName());
           out.println(filePart.getSize());
           out.println(filePart.getContentType());
           //output the inputstream of uploaded file
           inputstream=filePart.getInputStream();
        }
       else{
       out.println("cannot execute if condition");
        }
      %>
     <%
    try{
    String message=null;
    int id=123;
    String url="jdbc:mysql://localhost:3306/Project";
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection(url,"root","admin");
    String sql="INSERT INTO uploadfile(id,file) VALUES(?,?)";
    PreparedStatement stmt=con.prepareStatement(sql);
    stmt.setInt(1,id);
    if(inputstream!=null){
        stmt.setBlob(2,inputstream);
    }
    int row=stmt.executeUpdate();
    if(row>0){
        out.print("<h3><font color=red> Success Welcome!!!!!<br><br> </font></h3>");
    }
}catch(Exception e){
    e.printStackTrace();
}
//session.setAttribute("Message",message);
//response.sendRedirect("Message.jsp");
   %>

即使我选择了一个要上传的文件,filePart对象也会返回null。如果是bolck,它将终止,并返回"null cannot if condition“作为输出。

EN

回答 1

Stack Overflow用户

发布于 2014-02-20 18:46:37

为了回答实际问题,你得到一个空返回值的原因有两个。首先,代码:

代码语言:javascript
复制
   String str=request.getParameter("file");
   Part filePart=request.getPart(str);

应该只是简单地

代码语言:javascript
复制
   Part filePart = request.getPart("file");

但是,至关重要的是,request.getPart方法是Servlet3.0的一个特性,它需要使用带有@MultipartConfig注释的Servlet (而不是JSP文件)。

然而,代码中充斥着糟糕的实践。

正如评论中所述,十多年来一直不鼓励使用scriptlet;您应该首先将servlet用作某种控制器,然后使用以下内容(在内部)将其转发到JSP视图:

代码语言:javascript
复制
request.getRequestDispatcher("/WEB-INF/jsp/view.jsp").forward(request, response);

<font>和<center>超文本标记语言元素也已被弃用多年。

最后,有许多库可以帮助您上传文件。例如,Apache Commons FileUpload。

如何将上述所有内容放在一起的Here is a good example。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21904528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档