FileUpload的使用案例

			文件上傳
1、www.apache.org下載commons fileupload 和 commons io
2、創建jsp並附上如下代碼
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>

<%
String strId = request.getParameter("id");
int id = 0;
if(strId == null && strId.trim().equals("")){
	out.println("你選擇的商品有錯!");
	return;
}
id = Integer.parseInt(strId);
%>

<!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="../FileUpload" method="post" enctype="multipart/form-data" name="form1">
   <input type="hidden" name="id" value="<%=id %>">
  <input type="file" name="file">
  <input type="submit" name="Submit" value="upload">
</form>
<br>
<br>
    <form name="uploadform" method="POST" action="./servlet/FileUpload" ENCTYPE="multipart/form-data">

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

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

                        文件1:<input name="x" size="40" type="file">

        </td></tr>

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

                        文件2:<input name="y" size="40" type="file">

        </td></tr>

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

                        文件3:<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>
3、直接在項目下創建servlet並附上如下代碼
package com.cuijun.shopping.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class FileUpload extends HttpServlet {

	String uploadPath = "";
	
    @Override
	public void init(ServletConfig config) throws ServletException {
    	uploadPath = config.getInitParameter("uploadPath");
	}

	int id = -1;

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html; charset=GB18030");
		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:\\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()){
					if(item.getFieldName().equals("id")){
						id = Integer.parseInt(item.getString());
					}
				}
				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)));
							item.write(new File(uploadPath + id + ".jpg"));

							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);
		}

		// 保存上傳的文件到指定的目錄

		// 在下文中上傳文件至數據庫時,將對這裏改寫

	}

}
4、注意代碼中的路徑問題。千萬小心。
	1、路徑中\\代表\。不要寫成//。
	2、路徑後面不要忘記添加\\。
5、接受id。
	1、先定義int id = -1;
	2、判斷接受的域是正常域if (item.isFormField()){
					if(item.getFieldName().equals("id")){
						id = Integer.parse(item.getString());
					}
				}
	3、把上傳的文件寫到內存item.write(new File(uploadPath + id + ".jpg"));
6、修改WEB-INF下的配置文件
	1、添加<init-param>
			<param-name>uploadPath</param-name>
			<param-value>D:\\web\\Shopping\\WebContent\\image\\product\\</param-value>
		</init-param>
	2、在servlet中重寫init方法String uploadPath = "";
	
    @Override
	public void init(ServletConfig config) throws ServletException {
    	uploadPath = config.getInitParameter("uploadPath");
	}
7、Over!


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章