当前位置: 代码迷 >> Web前端 >> java中的文件预览跟下载
  详细解决方案

java中的文件预览跟下载

热度:445   发布时间:2014-01-28 12:05:40.0
java中的文件预览和下载

1、struts2实现预览

action中代码:

	private String downloadFileName;        
	public InputStream getDownloadFile() throws Exception
	{
		Map<String,String[]> param = super.getParameter();
		String imageFileId = ((String[])param.get("fileId"))[0];
		Integer fileId = new Integer( imageFileId );
		//根据fileId去库中查询文件名称
		String filename = activityService.getImageFileName(fileId).getImageFile();
		downloadFileName = filename;
		this.setDownloadFileName(downloadFileName);
		String fullPath = MisConst.IMAGE_FILE_PATH + "activity"+"/" + downloadFileName;	
        File file = new File( fullPath );
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }        
        return fis;
	}
	
	/**
	 * 下载附件
	 * @return
	 */
	public String download()
	{
		return SUCCESS;
	}

?xml中配置:

<action name="download" class="activityAction" method="download">
	<result name="success" type="stream">
		<param name="contentType">application/octet-stream </param>
		<param name="contentDisposition">filename=${downloadFileName}</param>
		<param name="inputName">downloadFile</param>//downloadFile要和action中getDownloadFile() 方法名一致
	</result>
</action>

?2、真正的下载

action:

/**
	 * 下载
	 * @return
	 * @throws Exception
	 */
	public String download() throws Exception{
		FileInputStream in=null;
		OutputStream out=null;
		try{
			String filename = ServletActionContext.getRequest().getParameter("filename");
			filename = URLDecoder.decode(filename.trim(), "utf-8");
			String filepath = ServletActionContext.getServletContext().getRealPath("\\upload\\takingFile")+"\\"+filename;
			File file = new File(filepath);
			byte[] buff = new byte[1024];
			in = new FileInputStream(file);
			HttpServletResponse response=ServletActionContext.getResponse();
			response.reset();
			out = response.getOutputStream();
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(file.getName(), "utf-8")+"\"");
			response.setHeader("Connection", "close");
            while (true) {
                int len = in.read(buff);
                if (len != -1) {
                    out.write(buff, 0, len);
                    out.flush();
                } else {
                    break;
                }
            }
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(in!=null){
				in.close();
			}
			if(out!=null){
				out.close();
			}
		}
		
		return null;
	}

?jsp:

function downLoad(filename){
	var filename = filename;
	var data="?filename="+encodeURI(encodeURI(filename));//注意两次转码,否则中文会乱码
	var url ="download.action";
       window.open(encodeURI(url)+data);
}

?

?

  相关解决方案