关闭

fileupload

489人阅读 评论(0) 收藏 举报

commons-fileupload需要commons-io支持。

1. 创建一个file,如果它的父节点不存在,则要mkdirs,然后createNewFile,否则直接createNewFile。

2. 用一个multipart/form-data的form,除了file类型的,普通文本类型的也可以,虽然request.getParameter得不到,但是通过fileupload可以得到。

3. upload.parseRequest(request).iterator()只能用一次,解决办法是List list = upload.parseRequest(request); list.iterator();分段进行,parse一次,iterator自然可以用多次。

package com.kiln;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Upload
 */
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Upload() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	private void createFile(File file){
		if(!file.exists()){
			String ps = file.getParent();
			if(ps!=null){
				File p = new File(ps);
				if(!p.exists())
					p.mkdirs();
			}
			try {
				file.createNewFile();
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);		
		if (isMultipart) {

			
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);

			Iterator items;
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			try {
				String id = null;
				List list =  upload.parseRequest(request);
				items = list.iterator();
				while(items.hasNext()){
					FileItem item = (FileItem) items.next();
					if(item.isFormField()){
						id = item.getString();
						break;	
					}									
				}
				if(id==null||id.equals("")){
					out.println("{res:false}");
					out.println();
					return;
				}
				items = list.iterator();
				while (items.hasNext()) {
					FileItem item = (FileItem) items.next();
					if (!item.isFormField()) {
						
						String name = item.getName();
						String fileName = name.substring(
								name.lastIndexOf('/') + 1, name.length());
						String extend = fileName.substring(fileName.lastIndexOf('.'),fileName.length());						
						Calendar c = Calendar.getInstance();
						c.setTime( new Date());
						StringBuffer fN = new StringBuffer(id);
						fN.append(c.get(Calendar.YEAR));
						fN.append(c.get(Calendar.MONTH));
						fN.append(c.get(Calendar.DAY_OF_MONTH));
						fN.append(c.get(Calendar.HOUR_OF_DAY));
						fN.append(c.get(Calendar.MINUTE));
						fN.append(c.get(Calendar.SECOND));
						fN.append(extend);
						fileName = fN.toString();
						String path = request.getRealPath("file")						
								+ File.separatorChar + fileName;						
						File uploadedFile = new File(path);
						createFile(uploadedFile);
						item.write(uploadedFile);			
						String returnPath = "http://localhost:8080"+request.getContextPath()+"/file/"+fileName;
						out.print("{url:"+returnPath+"}");
						out.close();
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:255439次
    • 积分:3624
    • 等级:
    • 排名:第9345名
    • 原创:98篇
    • 转载:52篇
    • 译文:1篇
    • 评论:51条
    文章分类
    最新评论