WEB开发文件上传与下载代码

/**
	 * 下载回避信息导入模板
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	public void downloadAvoidImportTemplete(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String realPath = this.getClass().getResource("/").getPath();
		String downloadFilePath = realPath+"/com/neeq/bpm/listing/sendfile/web/internal/avoidImportTemplete.xlsx";
		String downloadFileName="回避信息导入模板.xlsx";
		CtrlUtils.downloadFile(downloadFileName, downloadFilePath, response);
	}

public static void downloadFile(String downloadFileName, String downloadFilePath,HttpServletResponse response) throws Exception{
		FileNameMap fileNameMap=URLConnection.getFileNameMap();
		//附件名称,另存为的名称
		String contentType=fileNameMap.getContentTypeFor(downloadFileName);
		if(contentType==null){
			contentType="application/unknown";
		}
		response.reset();
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", "attachment;filename="+new String(downloadFileName.getBytes("gb2312"),"iso8859-1"));
		java.io.InputStream is=null;;
		OutputStream os=response.getOutputStream();
		try{
			if(!new File(downloadFilePath).exists()){throw new java.io.FileNotFoundException(downloadFilePath);}
			is=new FileInputStream(downloadFilePath);
			int count=512;
			byte[] bs=new byte[count];
			int length=-1;
			while((length=is.read(bs))!=-1){
				os.write(bs,0, length);
			}
			os.flush();
		}catch(IOException e){
			System.out.println("==========catch(IOException e):"+downloadFilePath);
			e.printStackTrace();
		}finally{
			if(is!=null)is.close();
			os.close();
		}
	}
	
	public static Map<String, Object> getMultipartFormData(HttpServletRequest request,HttpServletResponse res){
		DiskFileItemFactory  factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时,将产生临时文件并存储于临时目录中。   
		Map reqParaMap = new HashMap();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		try {
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String inputName=item.getFieldName();  
				if(item.isFormField()){
					String inputValue=item.getString();
					if(!StringUtils.isBlank(inputValue)){
						inputValue = new String(inputValue.getBytes("ISO-8859-1"),"utf-8");
						reqParaMap.put(inputName, inputValue);
					}
				}else if(!item.isFormField()){
					if(!StringUtils.isBlank(item.getName())){
						reqParaMap.put(inputName, item);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return reqParaMap;
    }
	public static String getReqMapPara(Map<String, Object> reqParaMap,String key){
		return reqParaMap.get(key)==null?null: (String)reqParaMap.get(key);
	}

猜你喜欢

转载自liushengit.iteye.com/blog/2327758