您的位置:首页 > 其它

利用commons-fileupload 上传图片(包含表单数据)

2018-02-02 15:52 369 查看
在一个表单中包含普通文本数据,另外还有需要上传的图片,那么本程序将图片保存到服务器上的一个图片目录中,文本数据则获取然后输出,查看传输是否正确,后面的处理为涉及。

上传的jsp页面:


最后将信息输出:(图片已经保存在特定目录中)



需要用到的两个jar包,commons-fileupload-1.2.2.jar  commons-io.jar

jsp页面:

[html] view
plain copy

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  

<%  

String path = request.getContextPath();  

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  

%>  

  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

<html>  

  <head>  

    <base href="<%=basePath%>">  

      

    <title>My JSP 'index.jsp' starting page</title>  

    <meta http-equiv="pragma" content="no-cache">  

    <meta http-equiv="cache-control" content="no-cache">  

    <meta http-equiv="expires" content="0">      

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  

    <meta http-equiv="description" content="This is my page">  

    <!-- 

    <link rel="stylesheet" type="text/css" href="styles.css"> 

    -->  

  </head>  

    

  <body>  

    <form id="form5" method="post" enctype="multipart/form-data" <strong> </strong> action="ReceiveFile" >  

     

    <table class="rounded-corner menu1" id="table_menu5" border="1px solid">  

        <thead align="center">  

            <tr>  

                <th>显示名称 </th>  

                <th>链接地址</th>  

            </tr>  

        </thead>  

        <tbody >  

            <tr class="odd" >  

                <td width="20%" align="center"><input value="中国青少年宫协会" readonly="readonly" name="input_value5" class="menu5_input1"></td>  

                <td width="50%" align="center"><input value="http://www.cnypa.org/" readonly="readonly" style="width: 500px;" name="input_value5"></td>  

            </tr>   

            <tr class="odd" >  

                <td width="20%" align="center"><input type="file"text" value="浏览" readonly="readonly" name="input_value5" class="menu5_input1"></td>  

                <td width="50%" align="center"><input value=""  style="width: 500px;" name="input_value5"></td>  

            </tr>   

            </tbody>  

        </table>  

  

    <table class="rounded-corner menu1" >  

        <tfoot align="right">  

        <tr>  

        <td></td>  

            <td>  

                <input type="submit"" value="保存" id="save5"  onclick="check5();">  

            </td>  

        </tr>  

        </tfoot>  

    </table>  

      

      

 </form>  

  </body>  

</html>  

servlet后台程序

[java] view
plain copy

package dai;  

  

  

import java.io.File;  

import java.io.IOException;  

import java.util.ArrayList;  

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 ReceiveFile extends HttpServlet {  

      

    private String uploadPath = "uploadpic/upload/"; // 上传文件的目录    

    private String tempPath = "uploadpic/uploadtmp/"; // 临时文件目录    

    private String serverPath = null;   

    private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"};  

    private int sizeMax = 5;//图片最大上限    

      

    @Override  

    protected void doPost(HttpServletRequest request, HttpServletResponse response)  

            throws ServletException, IOException {  

        // 服务器端根目录  

        String serverPath = getServletContext().getRealPath("/").replace("\\", "/");    

//        System.out.println(serverPath);  

        //Servlet初始化时执行,如果上传文件目录不存在则自动创建    

        if(!new File(serverPath+uploadPath).isDirectory()){   

            new File(serverPath+uploadPath).mkdirs();    

        }    

        if(!new File(serverPath+tempPath).isDirectory()){  

            new File(serverPath+tempPath).mkdirs();  

        }   

        DiskFileItemFactory factory = new DiskFileItemFactory();  

        factory.setSizeThreshold(5*1024); //最大缓存    

        factory.setRepository(new File(serverPath+tempPath));//临时文件目录    

            

        ServletFileUpload upload = new ServletFileUpload(factory);  

        upload.setSizeMax(sizeMax*1024*1024);//文件最大上限   

            

        String filePath = null;    

        try {    

            List<FileItem> items = upload.parseRequest(request);//获取所有文件列表   

            //  

            for (int i=0;i<items.size();i++) {  

                //里面一个for循环,获取一行的数据  

                FileItem item = items.get(i);  

<span style="white-space:pre">  </span>          if(!item.isFormField()){//文件名    

                    String fileName = item.getName().toLowerCase();  

                    if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){    

//                        String uuid = UUID.randomUUID().toString();    

                        filePath = serverPath+uploadPath+fileName;  

//                        System.out.println(filePath);  

                        File file = new File(filePath);  

                        item.write(file);  

                        System.out.println(fileName);  

                     }else {  

                        request.setAttribute("errorMsg", "上传失败,请确认上传的文件存在并且类型是图片!");  

                        request.getRequestDispatcher("uploaderror.jsp").forward(request,response);   

                    }  

                }else {  

                  //非文件流     

                    String value=item.getString();  

                    value = new String(value.getBytes("ISO-8859-1"),"UTF-8");  

//                    System.out.println(value);  

                    System.out.println(value);  

                }  

                  

            }   

        } catch (Exception e) {  

            e.printStackTrace();    

            request.setAttribute("errorMsg", "上传失败,请确认上传的文件存在并且类型是图片!");  

            request.getRequestDispatcher("uploaderror.jsp").forward(request,response);   

        }  

    }  

      

    @Override  

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  

            throws ServletException, IOException {  

        this.doPost(req, resp);  

    }  

}  

另外,文章中有几个注意点,像form表单的enctype="multipart/form-data" 需要注意,然后后台处理的时候需要将文件和普通文本数据分开处理,先说的大概,详细的下次再来编辑,源码的话我上传到这里:http://download.csdn.net/detail/xiaobaismiley/6333407
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: