首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

web Servlet中怎么使用上传组件FileUpload

2013-09-22 
web Servlet中如何使用上传组件FileUpload在web开发中要实现上传功能,就要用到上传组件FileUpload FileUpl

web Servlet中如何使用上传组件FileUpload

在web开发中要实现上传功能,就要用到上传组件FileUpload

FileUpload下载链接地址:http://archive.apache.org/dist/commons/fileupload/binaries/

Commons IO下载链接地址:http://commons.apache.org/proper/commons-io/


上传的服务器:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 

public class FileUpload extends HttpServlet {
    
    int id = -1;
    //String uploadPath2="";
    private static final long serialVersionUID = 1L;
     
    // location to store file uploaded
      private static final String UPLOAD_DIRECTORY = "upload";
//    private static final String UPLOAD_DIRECTORY = "images\\product\\";
 
    // upload settings
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
 
    @Override
    /*public void init(ServletConfig config) throws ServletException
    {
        uploadPath2 = config.getInitParameter("uploadfilepath");
    }
*/
    /**
     * Upon receiving file upload submission, parses the request to read
     * upload data and saves the file on disk.
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
 
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);
 
        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getRealPath("")
                + File.separator + UPLOAD_DIRECTORY;
         
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
 
        try {
            // parses the request's content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
 
            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems)
                {    
                     /**自己写的代码*/
                    if(item.isFormField())
                    {
                        if(item.getFieldName().equals("id"))
                        {
                            id = Integer.parseInt(item.getString());
                            //System.out.println(id);
                        }
                    }
                    
                    // processes only fields that are not form fields
                    if (!item.isFormField()) {

                      File storeFile = new File("F:\\svnTest\\webTest\\project\\Shopping2\\WebRoot\\images\\product\\"+ id + ".jpg");
 
                        // saves the file on disk
                        item.write(storeFile);
                        request.setAttribute("message",
                            "Upload has been done successfully!");
                    }
                   
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "There was an error: " + ex.getMessage());
        }
        // redirects client to message page
        getServletContext().getRequestDispatcher("/admin/message.jsp").forward(
                request, response);
    }
     
}

ProductUpload.jsp(上传的客户端)

<%@ page language="java" contentType="text/html; charset=GB18030" import="com.zhaoming.shopping.*, java.util.*"
    pageEncoding="GB18030"%>

<%
int id = Integer.parseInt(request.getParameter("id"));
%>

<!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=UTF-8">
<title>File Upload Demo</title>
</head>
<body>
    <center>
        <form method="post" action="../servlet/FileUpload" enctype="multipart/form-data">
            <input type="hidden" name="id" value=<%=id %>>
            Select file to upload:
            <input type="file" name="uploadFile" />
            <br/><br/>
            <input type="submit" value="Upload" />
        </form>
    </center>
</body>
</html>


message.jsp(显示上传成功)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Upload Result</title>
</head>
<body>
    <center>
        <h2>${message}</h2>
    </center>
</body>
</html>


web.xml

?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>FileUpload</servlet-name>
    <servlet-class>com.zhaoming.shopping.servlet.FileUpload</servlet-class> 
  </servlet>

<servlet-mapping>
    <servlet-name>FileUpload</servlet-name>
    <url-pattern>/servlet/FileUpload</url-pattern>
  </servlet-mapping>



热点排行