在jsp中上传文件

时间:2015-02-15 10:37:01

标签: jsp

文件上传部分存在问题。

这是代码

<form action="uploadlogoc.jsp" method="post" enctype="multipart/form-data">
<table align="center">
<tr><td>
USER:</td><td><select name="userDetails">
<%
while(rs.next()){%>
<option><%=rs.getString("username") %></option>
<%} %>
</select>
</td></tr>
<tr><td>Subject</td><td><input type="text" name="subject"/></td></tr>
<tr>
<td>File:</td><td><input type="file" name="file" size="25"></td>
</tr>
<tr><td></td><td><input type="submit" name="s1" value="Uploadfile"><td></td>
</tr>
</table>

由于存在enctype,因此不应将主题字段和用户名字段中的值传递到下一页。当我们删除它时,值将通过,但文件不会上传。是什么原因?

Connection cone=null;
Statement smt=null;
ResultSet rs=null;
DbConnection con=new DbConnection();
try{
cone=con.Connection();
String sql="SELECT * FROM reg";
smt=cone.createStatement();
rs=smt.executeQuery(sql);
}
catch(Exception e){
e.printStackTrace();
}
%>

3 个答案:

答案 0 :(得分:1)

要上传文件,我们必须使用enctype =&#34; multipart / form-data&#34; 但如果将其与一些文本字段一起使用,则解析这些字段(request.getParameter)将返回null 所以我们必须遵循另一个程序 我们将使用form.jsp,upload.java,display.jsp

<html>
<head></head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
Name:<input type="text" name="text">
<br>
Select File to Upload:<input type="file" name="fileName">
<input type="submit" value="Upload">
</form>
</body>
</html>
package helper;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.util.Streams;


/**
 * Servlet implementation class upload
 */
@WebServlet("/upload")
@MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB 
maxFileSize=1024*1024*50,       // 50 MB
maxRequestSize=1024*1024*100)       // 100 MB
public class upload extends HttpServlet {

private static final long serialVersionUID = 1L;
 private static final String UPLOAD_DIR = "new";
/**
 * @see HttpServlet#HttpServlet()
 */
public upload() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse    response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    // gets absolute path of the web application
    String applicationPath = request.getServletContext().getRealPath("");
 // constructs path of the directory to save uploaded file
    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
    //Declare fields for storing parse values from user
    String name="";
    //url which you will store in database
    String url="";
 // creates the save directory if it does not exists
    File fileSaveDir = new File(uploadFilePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }

    //Contains fileName
    String fileName = null;


    int i=0;
    //Get all the parts from request and write it to the file on server

    for (Part part : request.getParts()) {
       fileName = getFileName(part);           
       InputStream stream=part.getInputStream();

       if(!fileName.equals("NOT_AN_IMAGE")){
       url=fileName;
       //Stores the file in the respective directory
       part.write(uploadFilePath + File.separator + fileName);
       }
       else{
           String user_input=Streams.asString(stream);
           i++;
            switch(i){
            case 1:name=user_input;
            break;  
            }      
        }


    }

//Insert String url as path in the database
    HttpSession session=request.getSession(true);
    //Storing url of the current file which is uploaded as attribute
    String path=UPLOAD_DIR+"\\"+url;
    //Input text field name
    System.out.println(path);
    System.out.println(name);
    session.setAttribute("field", name);
    session.setAttribute("link",path);
    RequestDispatcher rd=request.getRequestDispatcher("display.jsp");
    rd.forward(request,response);


}

//Finding whether it is file or text
private String getFileName(Part part) {

        String contentDisp = part.getHeader("content-disposition");
        System.out.println("content-disposition header= "+contentDisp);
        String[] tokens = contentDisp.split(";");
        String msg="NOT_AN_IMAGE";
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return msg;
    }

}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body align="center">
<h1 align="center">
<c:out value="${sessionScope.field}"/></h1>

<img src=<c:out value="${sessionScope.link}"/>  width="306" height="208">
</body>
</html>

答案 1 :(得分:0)

  

当我们删除它时,值将通过,但文件不会上传。

您无法删除enctype='multipart/form-data',当您发出 POST 请求时,您必须以某种方式对构成请求正文的数据进行编码。

编码 POST 请求的方法有很多,但是,当您编写客户端代码时,只需在表单包含multipart/form-data时使用<input type="file">即可。 } elements。

使用encTypeServlet Class

而不是使用

request.getParameter("parameterName");

使用

MultipartRequest#getParameter("parametername");

答案 2 :(得分:0)