`
酷的飞上天空
  • 浏览: 518547 次
  • 性别: Icon_minigender_1
  • 来自: 无锡
社区版块
存档分类
最新评论

简单文件上传

阅读更多

一个blog的上传功能当然是必不可少的,本例使用commons-fileupload-1.2.1实现

写了个接口如下,

public interface FileUpLoad {

	public int getFileSize(String fieldName);
	/**
	 * 取得上传文件的文件名
	 * @param fieldName
	 * @return
	 */
	public String getUpFileName(String fieldName);
	/**
	 * 取得普通字段的值
	 * @param name
	 * @return
	 */
	public String getValueOfParameter(String fieldName);
	/**
	 * 根据字段名称取得上传文件
	 * @param fieldName
	 * @return
	 */
	public File getFile(String fieldName);
	/**
	 * 如果此字段不属于文件上传,则返回null
	 * @param fieldName
	 * @return
	 */
	public String getFileType(String fieldName);
	/**
	 * 移动文件到targetFile,如果字段不是上传域则抛出RuntimeException。调用完成后源文件删除
	 * @param fieldName 上传域的字段
	 * @param targetFile 目标文件
	 */
	public void moveFile(String fieldName,File targetFile);
}

  

简单实现类如下

public class SimpleFileUpLoad implements FileUpLoad{

	private Map<String, String> mapOfString = new HashMap<String, String>();
	private Map<String, FileItem> mapOfFile = new HashMap<String, FileItem>();
	/**
	 * 
	 * @param tmpPath 临时文件位置
	 * @param maxSize 单个文件最大数,单位是KByte
	 * @param request  
	 * @throws FileUploadException 超过最大限制抛出
	 * @throws IOException 解析失败抛出
	 */
	@SuppressWarnings("unchecked")
	public SimpleFileUpLoad(String tmpPath,int maxSize,HttpServletRequest request) throws FileUploadException, IOException{
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//设置内存的最大数单位是bytes,超过了则存在硬盘上
		factory.setSizeThreshold(4096);
		//设置临时文件的目录
		factory.setRepository(new File(tmpPath));
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		//设置单个文件的最大大小,单位是bytes
		servletFileUpload.setFileSizeMax(maxSize*1024);
		//设置编码方式,为了防止中文乱码
		servletFileUpload.setHeaderEncoding("UTF-8");
		List<FileItem> fileItems = servletFileUpload.parseRequest(request);
		Iterator<FileItem> it = fileItems.iterator();
		while(it.hasNext()){
			FileItem fileItem = it.next();
			if(fileItem.isFormField()){
				try {
					//取得非上传域的表单字段,存在放置表单字段的map里面,字段名为key
					mapOfString.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
				} catch (UnsupportedEncodingException e) {
					// UTF-8  why isn't a unCheckException?
				}
			}
			else{
				if(fileItem.getName()!=null && !fileItem.getName().equals("")){
					//将上传文件对应的FileItem对象,存在文件的map里面,字段名为key
					mapOfFile.put(fileItem.getFieldName(),fileItem);
				}
			}
		}
	}
	//获得文件按的尺寸,没用到,因为一直返回0,所以从使用上传后的文件对象中获得大小。
	@Override
	public int getFileSize(String fieldName) {
		if(!mapOfFile.containsKey(fieldName)) return 0;
		return (int)mapOfFile.get(fieldName).getSize();
	}
	//返回上传文件的文件名,截取后的文件名,非全路径
	@Override
	public String getUpFileName(String fieldName) {
		if(!mapOfFile.containsKey(fieldName)) return null;
		String fileName = mapOfFile.get(fieldName).getName();
		if(fileName.lastIndexOf("/")!=-1){
			//linux
			fileName = fileName.substring(fileName.lastIndexOf("/")+1);
		}else fileName = fileName.substring(fileName.lastIndexOf("\\")+1);//windos
		return fileName;
	}
	@Override
	public File getFile(String fieldName) {
		if(!mapOfFile.containsKey(fieldName)) return null;
		return new File(mapOfFile.get(fieldName).getName());
	}
	//返回上传文件的类型,不过没用到这个功能。
	@Override
	public String getFileType(String fieldName) {
		if(!mapOfFile.containsKey(fieldName)) return null;
		return mapOfFile.get(fieldName).getContentType();
	}
	@Override
	public String getValueOfParameter(String fieldName) {
		return mapOfString.get(fieldName);
	}
	@Override
	public void moveFile(String fieldName, File targetFile) {
		if(!mapOfFile.containsKey(fieldName)) throw new RuntimeException("上传文件不存在!");
		try {
			//写入新文件
			mapOfFile.get(fieldName).write(targetFile);
			//然后删除临时文件
			mapOfFile.get(fieldName).delete();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}

 

使用的例子如下,以用于文件上传的servlet为例

public class DownFileServlet extends AbstractServlet {

	private static final long serialVersionUID = 1L;
	//get方法用于显示上传的文件
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<DownFile> downFileList = DaoFactory.getDownFileDao().getDownFileList();
		BindData(req, "downFileList", downFileList);
		forward("downfcontrol.jsp", req, resp);
	}
	//post方法用于处理上传文件的表单数据,完成后返回传页面
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String savePath = getServletContext().getRealPath("/down");
		DownFile df = new DownFile();
		FileUpLoad FileUpLoad=null;
		String upFileName;
		String saveName;
		try {
			//设置上传文件最大10M
			FileUpLoad = new SimpleFileUpLoad(getTmp(), 10*1024, req);
		} catch (FileUploadException e) {
			BindData(req, "errorMsg", "上传文件失败!e:"+e.toString());
			forwardResultPage(req, resp);
			return;
		}
		
		upFileName = FileUpLoad.getUpFileName("upfile");
		if(upFileName==null){
			BindData(req, "errorMsg", "上传文件失败!上传文件不存在");
			forwardResultPage(req, resp);
			return;			
		}
		//保存的实际文件名为当前时间的字符串形式,加上源文件的最后一个后缀名。如无后缀则只是时间按作为文件名
		saveName = Calendar.getInstance().getTimeInMillis()+"";
		if(upFileName.lastIndexOf(".")!=-1)
			saveName = saveName+upFileName.substring(upFileName.lastIndexOf("."));
		File saveFile = new File(savePath,saveName);
		//将临时文件拷贝到保存目录
		FileUpLoad.moveFile("upfile", saveFile);
		
		df.setDownFileName(upFileName);
		df.setDownFilePath(saveName);
		df.setDownFileSize((int)saveFile.length()/1024+1);
		
		DaoFactory.getDownFileDao().addDownFile(df);
		sendRedirect("admin/downfcontrol.htm", req, resp);
	}

}

 

 

很简单,不再介绍,jsp文件也不再贴出

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics