자바 파일 미리 보기 및 다운로드

2507 단어 도구 클래스
package com.souche.json;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
@Api(value = "MyTest", description = "  ")
@Controller
public class MyTest {

	
	@ApiOperation(value = "  ",httpMethod="GET")
	@RequestMapping("readAndDownload.do")
	public void readAndDownload(HttpServletResponse res, String params)  {
		InputStream in = null;
		OutputStream out = null;
		String filePaths = "/Users/zhaobin/git/saas_cm_svc/web/config/optimus/properties/***.docx";
		if (filePaths != null) {
			boolean c = new File(filePaths).exists();
			try {
				in = new FileInputStream(filePaths);

				//      
				//       
				//    :       
				if ("dwld".equalsIgnoreCase(params)) {
					res.setContentType("application/force-download");

					res.setContentLength(in.available());
				} else {
					res.setContentType("application/pdf");
				}
				String userAgent = request.getHeader("User-Agent").toLowerCase();  
				String fileName="    ";
			if (userAgent.contains("msie") || userAgent.contains("trident") ) {  
			    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");  
			} else {  
			    //  IE      :  
			    fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");  
			}  
			//response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\""); 
				//    :    copy
				out = res.getOutputStream();
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = in.read(b)) != -1) {
					out.write(b, 0, len);
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}

좋은 웹페이지 즐겨찾기