日期:2014-05-16  浏览次数:20871 次

文件上传与下载Apache的Servlet实现
package cn.com.infcn.server.qyqz;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.com.infcn.common.jdbc.SqlOperate;

@SuppressWarnings("serial")
public class Upload {
File tempPathFile;
/**
* 文件上传
* @param request
* @param response
* @return
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unchecked")
public String fileUpload(HttpServletRequest request, HttpServletResponse response,String uuid) throws UnsupportedEncodingException {
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
String result = "fail";
String errortype[] = { ".exe", ".com", ".cgi", ".asp" };
String theTrueName[] = new String[1];
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy\\MM\\dd\\HH");
String pathdir = "\\uploadfile\\qyqz\\"+ dateformat.format(new Date());//构建文件保存的目录
//得到图片保存目录的真实路径
String uploadPath = request.getSession().getServletContext().getRealPath(pathdir);
File savedir = new File(uploadPath);
if(!savedir.exists()) savedir.mkdirs();//如果目录不存在就创建
String tempPath = uploadPath + "\\temp";
File tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Set factory constraints
factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);// 设置缓冲区目录

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB

List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
Iterator<FileItem> it = items.iterator();
File fullFile = null;
String uuidname =null;
String type = null;
String realname = null;
while (it.hasNext()) {
FileItem fileitem = (FileItem) it.next();
// 如果这个fileitem对象的FiledName是四个以上的字符,并前四个字符是file,并且不是上传的文件元素的话,那就是三个hidden对象中的一个了
if (fileitem.getFieldName().length() > 2
&& "groupid".equals(fileitem.getFieldName()) && fileitem.isFormField()) {
// 设置对应的文件名,由于参数名的最后一位是从1开始的,所以减一.
theTrueName[0] = fileitem.getString();
}

// 判断文件名当中是否有不合法的文件的后缀
for (int i = 0; i < errortype.length; ++i) {
for (String name : theTrueName) {
// 有时可能只有一个文件上传,其他两个的文件名值会为null,为避免空指针异常,加上如下判断。
// 当name为null时,跳出循环.
if (name == null)
break;
if (name.endsWith(errortype[i])) {
// 如果有就抛异常
throw new Exception(name + " is wrong type");
}
}
}
String fileName = fil