首页 > 代码库 > 多张图片上传简单示例

多张图片上传简单示例

说是原创,其实也是参考了众多网上的贴子,非常感谢那些无私奉献的前辈们!

这个项目在要用到fileupload包及相关的io包(我上传到网上了,大家可以免费下载),

另外也可以用struts2包,为了省事我把整个struts2-core-2.3.24.1的包都导进项目里了,该包里面包含了上传用到的所有包。

struts2包可以从官网上下载:http://struts.apache.org/download.cgi#struts23241


1、上传多个图片是要注意

第一:<form id="form1" name="form1" method="post" action="../servlet/fileServlet"

 enctype="multipart/form-data">

 中的“enctype="multipart/form-data"”是必须要写的。

第二:<input name="file" type="file" size="20" multiple/>

中的“multiple”必须要写上,不然只能单选。注:html5后才支持multiple这个属性

//*********************************  目录结构  ***************************

//见“博文附件”

代码如下:

//*****************************  jsp代码 ***************************************

//index.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"

    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>Insert title here</title>

</head>

<body>

    <a href="http://www.mamicode.com/upload/upload2.jsp">多个文件上传</a>

</body>

</html>


///////////////////////////////////////////////////////

//upload2.jsp代码(是上传文件的界面)

<%@ page language="java" contentType="text/html; charset=UTF-8"

    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>多张图片上传</title>

</head>

<body>

<a href="http://www.mamicode.com/index.jsp">首页</a>

<hr>


<p align="center"> 请您选择需要上传的文件</p>

<form id="form1" name="form1" method="post" action="../servlet/fileServlet" enctype="multipart/form-data">

上传文件:<input name="file" type="file" size="20" multiple/>

<br>

    <input type="submit" name="submit" value="http://www.mamicode.com/提交" >

    <input type="reset" name="reset" value="http://www.mamicode.com/重置" >

<br>

</form>

</body>

</html>

/////////////////////////////////////////////////////////////////

//uploadResult.jsp代码(是显示上传结果的界面)

<%@ page language="java" contentType="text/html; charset=UTF-8"

    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>uploadResult</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="http://www.mamicode.com/styles.css">

 -->


  </head>

  

  <body>

  ${requestScope[‘upload.message‘] }

    <a href="http://www.mamicode.com/upload/upload2.jsp">上传文件</a>

  </body>

</html>

//******************************  web.xml  **********************************

//web.xml代码

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>fileUp1</display-name>

  

   <servlet>

   <servlet-name>FileUploadServlet</servlet-name>

    <servlet-class>com.li.servlet.FileUploadServlet</servlet-class>

    <init-param>

     <param-name>savePath</param-name>

     <param-value>D:/uploads</param-value>

    </init-param>

  </servlet>


  <servlet-mapping>

    <servlet-name>FileUploadServlet</servlet-name>

    <url-pattern>/servlet/fileServlet</url-pattern>

  </servlet-mapping>

<welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

//***************************** servlet代码 ***************************

//FileUploadServlet.java

package com.li.servlet;


import java.io.File;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;


import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

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.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.struts2.ServletActionContext;


/**

 * Servlet implementation class FileUploadServlet

 */

@WebServlet("/FileUploadServlet")

public class FileUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private ServletContext sc;

private String savePath;

private File uploadPath;       

   

public void doGet(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, IOException {

 doPost(request, response);

}

 


public void init(ServletConfig config) {

 // 在web.xml中设置的一个初始化参数

 savePath = config.getInitParameter("savePath");

 sc = config.getServletContext();

 uploadPath = new File(getPath()); 

 //在初始化时,检查上传图片的文件夹和存放临时文件的文件夹是否存在,如果不存在,就创建 

      if (!uploadPath.exists()) {

          uploadPath.mkdir();  

      }  

        }


 

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 request.setCharacterEncoding("UTF-8");

 DiskFileItemFactory factory = new DiskFileItemFactory();

 ServletFileUpload upload = new ServletFileUpload(factory);

 try {

  List items = upload.parseRequest(request);

  Iterator itr = items.iterator();

  while (itr.hasNext()) {

   FileItem item = (FileItem) itr.next();

   if (item.isFormField()) {

    System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));

   } else {

    if (item.getName() != null && !item.getName().equals("")) {

     System.out.println("上传文件的大小:" + item.getSize());

     System.out.println("上传文件的类型:" + item.getContentType());

     // item.getName()返回上传文件在客户端的完整路径名称

     System.out.println("上传文件的名称:" + item.getName());

     File tempFile = new File(item.getName());

     //上传文件的保存路径

     File file = new File(getPath(), tempFile.getName());

     item.write(file);

     request.setAttribute("upload.message", "上传文件成功!");

    }else{

     request.setAttribute("upload.message", "没有选择上传文件!");

    }

   }

  }

 }catch(FileUploadException e){

  e.printStackTrace();

 } catch (Exception e) {

  e.printStackTrace();

  request.setAttribute("upload.message", "上传文件失败!");

 }

 request.getRequestDispatcher("../upload/uploadResult.jsp").forward(request, response);

}

 

public String getPath(){ 

return savePath.indexOf(":")>0?savePath:sc.getRealPath("/") + savePath;

}

}

//上面的代码可以保存在指定的盘符下或服务器上,只需更改web.xml的参数就可以了;

//放在服务器的坏处是一但在服务器重新布置项目且没有及时备份文件的情况下,容易造成以前的图片丢失。


多张图片上传简单示例