基于servlet实现上传图片

jsp文件上传大多采用开源项目Commons FileUpload来简化处理,可以在http://jakarta.apache.org/commons/fileupload/下载,

这个包需要Commons IO的支持,可以在http://jakarta.apache.org/commons/io/下载。Commons FileUpload提供三种文件上传处理方式,DiskFileUpload、

ServletFileUpload和 PortletFileUpload三种方式,

其中DiskFileUpload已经在javadoc下已经被标记为过期的方法,建议用 ServletFileUpload代替,

而PortletFileUpload需要配合portlet-api来使用,所以这里我们只介绍 ServletFileUpload,并且这个也是最常用的


第一步:配置web.xml 

======================================================================

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--servlet 基本配置-->
    <servlet>
        <servlet-name>multipart</servlet-name>
        <servlet-class>com.test.servlet.MultipartTestServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>multipart</servlet-name>
        <url-pattern>/submitServlet</url-pattern>
    </servlet-mapping>

</web-app>
======================================================================

第二步:jsp页面

=======================================================================

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传图片</title>
</head>
<body>
<h2>上传图片</h2>
<form action="submitServlet" enctype="multipart/form-data" method="post">
  <input type="text" name="username" /><br />
  <input type="file" name="myfile" /><br/>
  <input type="file" name="myfile" /><br/>
  <input type="submit" />
</form>
</body>
</html>

======================================================================

第三步:servlet 的实现

======================================================================

package com.test.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by jerei on 2017/3/19.
 */
public class MultipartTestServlet extends HttpServlet {

    public MultipartTestServlet() {
        super();
    }

    /**
     * 业务的实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("上传开始...");
        req.setCharacterEncoding("utf-8");
        RequestContext requestContext = new ServletRequestContext(req);
        //判断是否是multipart/form-data格式的数据类型
        if(FileUpload.isMultipartContent(requestContext)){
            /**
             * 将请求消息实体中的每一个项目封装成单独的DiskFileItem (FileItem接口的实现) 对象的任务
             *org.apache.commons.fileupload.FileItemFactory 接口的默认实现
             *org.apache.commons.fileupload.disk.DiskFileItemFactory 来完成。当上传的文件项目比较小时,
             *直接保存在内存中(速度比较快),比较大时,以临时文件的形式,保存在磁盘临时文件夹(虽然速度慢些,但是内存资源是有限的)。
             */
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(new File("D:/Upload/test"));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(2000000);
            List items = new ArrayList();
            try {
                items = upload.parseRequest(req);
            } catch (FileUploadException e1) {
                System.out.println("文件上传发生错误" + e1.getMessage());
            }
            Iterator it = items.iterator();
            while(it.hasNext()){
                FileItem fileItem = (FileItem) it.next();
                if(fileItem.isFormField()){
                    System.out.println(fileItem.getFieldName() + "   " + fileItem.getName() + "   " + new String
                            (fileItem.getString().getBytes("iso8859-1"), "utf-8"));
                }else{
                    System.out.println(fileItem.getFieldName() + "   " +
                            fileItem.getName() + "   " + fileItem.isInMemory() + "    " +
                            fileItem.getContentType() + "   " + fileItem.getSize());
                    //
                    if(fileItem.getName()!=null && fileItem.getSize()!=0){
                        File fullFile = new File(fileItem.getName());
                        File newFile = new File("D:/Upload/test" + fullFile.getName());
                        try {
                            fileItem.write(newFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else{
                        System.out.println("文件没有选择 或 文件内容为空");
                    }
                }
            }
        }
    }

}

=====================================================================

注意:form表单中antion的设置,与web.xml 中的

<url-pattern>/submitServlet</url-pattern>

相对比 缺少"/",切记。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值