java下载文件

使用原生servlet下载

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//获取保存在服务器的真实路径
		String path = request.getServletContext().getRealPath("/images");
		//获取文件名
		String wj = "yy图标.jpg";
		//复制该文件
		File file = new File(path, wj);
		//获取输入流,读取复制的文件
		InputStream is=new FileInputStream(file);
		//获取输出流
		OutputStream os = response.getOutputStream();
		//添加头文件,如果是中文转换编码格式
		response.setHeader("content-disposition","attachment;filename=" +new String(wj.getBytes("utf-8"),"iso-8859-1"));
		
		byte[] b = new byte[1024];
		int len = is.read(b);
		while(len!=-1){
			os.write(b,0,len);
			len = is.read(b);
		}
		os.close();
		is.close();
	}

使用SpringMVC下载

@RequestMapping("downFile")
	  public ResponseEntity<byte[]> export( String fileName) throws IOException {  
	  //获取文件名及文件路径
		 String filePath = "E:/img/"+fileName;
		 //设置头文件
	        HttpHeaders headers = new HttpHeaders();    
	        File file = new File(filePath);
	        //防止中文乱码
	        fileName =  new String(fileName.getBytes("utf-8"),"iso-8859-1");
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    
	        headers.setContentDispositionFormData("attachment", fileName);          
	       	ResponseEntity<byte[]> files = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
	        return files;  
	    }

只用Struts2下载

public class DownFileAction {
    private String fileName;
    private InputStream inputStream;
    public String down(){
    	inputStream = ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
    	try {
    		
			fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return "success";
    }
    //此处省略set方法
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值