您好,登錄后才能下訂單哦!
說是原創(chuàng),其實也是參考了眾多網(wǎng)上的貼子,非常感謝那些無私奉獻的前輩們!
這個項目在要用到fileupload包及相關(guān)的io包(我上傳到網(wǎng)上了,大家可以免費下載),
另外也可以用struts2包,為了省事我把整個struts2-core-2.3.24.1的包都導(dǎo)進項目里了,該包里面包含了上傳用到的所有包。
struts2包可以從官網(wǎng)上下載: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這個屬性
//********************************* 目錄結(jié)構(gòu) ***************************
//見“博文附件”
代碼如下:
//***************************** 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="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="../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="提交" >
<input type="reset" name="reset" value="重置" >
<br>
</form>
</body>
</html>
/////////////////////////////////////////////////////////////////
//uploadResult.jsp代碼(是顯示上傳結(jié)果的界面)
<%@ 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="styles.css">
-->
</head>
<body>
${requestScope['upload.message'] }
<a href="../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中設(shè)置的一個初始化參數(shù)
savePath = config.getInitParameter("savePath");
sc = config.getServletContext();
uploadPath = new File(getPath());
//在初始化時,檢查上傳圖片的文件夾和存放臨時文件的文件夾是否存在,如果不存在,就創(chuàng)建
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("表單參數(shù)名:" + item.getFieldName() + ",表單參數(shù)值:" + 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;
}
}
//上面的代碼可以保存在指定的盤符下或服務(wù)器上,只需更改web.xml的參數(shù)就可以了;
//放在服務(wù)器的壞處是一但在服務(wù)器重新布置項目且沒有及時備份文件的情況下,容易造成以前的圖片丟失。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。