【Java基礎】--上傳檔案

ZeroWM發表於2016-02-12


  專案中常常涉及到檔案上傳的功能,如圖所示,我們上傳一個 2.jpg的圖片檔案,



  上傳成功後顯示上傳的圖片源路徑,圖片上傳到D盤根目錄下面:


要實現該功能,我們需要引用如下的jar包:

commons-fileupload-1.1.1.jar

commons-io-1.2.jar


如圖所示:


右鍵專案-Build Path - Add External Archives-選中需要新增的jar包(注意不是zip哦),jar即可引用成功。


上傳使用的servlet如下,FileUploadServlet:

<span style="font-family:Microsoft YaHei;font-size:14px;">package com.bjpowernode.drp.basedata.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

	 /**
	  * Destruction of the servlet. <br>
	  */
	 private String uploadPath = "D:\\addnetFile\\"; // 用於存放上傳檔案的目錄
	    private File tempPath =new File("D:\\addnetFile\\tmp\\"); // 用於存放臨時檔案的目錄
	 public void destroy() {
	  super.destroy(); // Just puts "destroy" string in log
	  // Put your code here
	 }

	 /**
	  * The doPost method of the servlet. <br>
	  *
	  * This method is called when a form has its tag value method equals to post.
	  *
	  * @param request the request send by the client to the server
	  * @param response the response send by the server to the client
	  * @throws ServletException if an error occurred
	  * @throws IOException if an error occurred
	  */
	  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
	   res.setContentType( "text/html; charset=GB2312");
	  PrintWriter out=res.getWriter();
	  System.out.println(req.getContentLength());
	     System.out.println(req.getContentType());
	   DiskFileItemFactory factory = new DiskFileItemFactory();
	        // maximum size that will be stored in memory
	        factory.setSizeThreshold(4096);
	        // the location for saving data that is larger than getSizeThreshold()
	        factory.setRepository(new File("d:\\File\\addnetFile\\temp"));

	        ServletFileUpload upload = new ServletFileUpload(factory);
	        // maximum size before a FileUploadException will be thrown
	        upload.setSizeMax(1000000);
	        try{
	        List fileItems = upload.parseRequest(req);
	        // assume we know there are two files. The first file is a small
	        // text file, the second is unknown and is written to a file on
	        // the server
	        Iterator iter = fileItems.iterator();

	//  正則匹配,過濾路徑取檔名
	     String regExp=".+\\\\(.+)$";

	//  過濾掉的檔案型別
	  String[] errorType={".exe",".com",".cgi",".asp"};
	     Pattern p = Pattern.compile(regExp);
	        while (iter.hasNext()) {
	         FileItem item = (FileItem)iter.next();
	         //忽略其他不是檔案域的所有表單資訊
	         if (!item.isFormField()) {
	             String name = item.getName();
	             long size = item.getSize();
	             if((name==null||name.equals("")) && size==0)
	                 continue;
	          Matcher m = p.matcher(name);
	         boolean result = m.find();
	         if (result){
	             for (int temp=0;temp<errorType.length;temp++){
	             if (m.group(1).endsWith(errorType[temp])){
	                   throw new IOException(name+": wrong type");
	             }
	             }
	             try{

//	        儲存上傳的檔案到指定的目錄

//	        在下文中上傳檔案至資料庫時,將對這裡改寫
	                     item.write(new File("d:\\" + m.group(1)));

	                   out.print(name+"  "+size+"<br>");
	                   }
	                   catch(Exception e){
	                     out.println(e);
	                   }

	                }
	               else
	               {
	                 throw new IOException("fail to upload");
	               }
	               }
	           }
	        }
	         catch (IOException e){
	           out.println(e);
	         }
	         catch (FileUploadException e){
	              out.println(e);
	         }

	//  儲存上傳的檔案到指定的目錄

	//  在下文中上傳檔案至資料庫時,將對這裡改寫

	    }


	 /**
	  * Initialization of the servlet. <br>
	  *
	  * @throws ServletException if an error occure
	  */
	 public void init() throws ServletException {
	  // Put your code here
	 }
}
</span>


頁面test_upload.html程式碼:

<span style="font-family:Microsoft YaHei;font-size:14px;"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>index.html</title>

		<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 action="./servlet/item/FileUploadServlet" method="post"
			enctype="multipart/form-data" name="form1">
			<input type="file" name="file">
			<input type="submit" name="Submit" value="upload">
		</form>
		<form action="./servlet/HelloWord" method="post">
			<input type="submit" />
		</form>
		<form name="uploadform" method="POST" action="./servlet/item/FileUploadServlet"
			ENCTYPE="multipart/form-data">

			<table border="1" width="450" cellpadding="4" cellspacing="2"
				bordercolor="#9BD7FF">

				<tr>
					<td width="100%" colspan="2">

						
						<input name="x" size="40" type="file">

					</td>
				</tr>

				<tr>
					<td width="100%" colspan="2">

						
						<input name="y" size="40" type="file">

					</td>
				</tr>

				<tr>
					<td width="100%" colspan="2">

						
						<input name="z" size="40" type="file">

					</td>
				</tr>

			</table>

			<br />
			<br />

			<table>

				<tr>
					<td align="center">
						<input name="upload" type="submit" value="��ʼ�ϴ�" />
					</td>
				</tr>

			</table>

		</form>

	</body>
</html></span>


web.xml:

<span style="font-family:Microsoft YaHei;font-size:14px;">	<servlet>
		<servlet-name>FileUploadServlet</servlet-name>
		<servlet-class>com.bjpowernode.drp.basedata.web.FileUploadServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>FileUploadServlet</servlet-name>
		<url-pattern>/servlet/item/FileUploadServlet</url-pattern>
	</servlet-mapping></span>


  把這些程式碼整合到一起,即可實現檔案的上傳功能。


相關文章