欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java通过url下载文件并输出的方法

程序员文章站 2023-12-14 23:06:52
实例如下所示: controller: @requestmapping(value = "/{loanid}/{atmttype}") public voi...

实例如下所示:

controller:
@requestmapping(value = "/{loanid}/{atmttype}")
 public void doget(@pathvariable("loanid") string loanid,@pathvariable("atmttype") string atmttype,
   httpservletrequest req,httpservletresponse response) {
  map<string,string> map = new hashmap<string,string>();
  map.put("loanid", loanid);
  map<string, string> urlbyloanid= new hashmap<string,string>();
 // map<string, string> urlbyloanid = zcmqueryinfoservice.queryurlbyloanid(map);
  try {
   if(urlbyloanid!=null){
    string wjurl="http://10.0.15.11:8080/gateway//nfs/marvel-core-admin/2017/10/11/compact_seal_17101119371231615_7.pdf";
    //string wjurl = urlbyloanid.get("url");
    int i = wjurl.lastindexof("/");
    string filename = wjurl.substring(i+1);
    
    url url = new url(wjurl); 
    httpurlconnection conn = (httpurlconnection)url.openconnection(); 
    //设置超时间为3秒 
    conn.setconnecttimeout(3*1000); 
    //防止屏蔽程序抓取而返回403错误 
    conn.setrequestproperty("user-agent", "mozilla/4.0 (compatible; msie 5.0; windows nt; digext)"); 
    //得到输入流 
    inputstream inputstream = conn.getinputstream(); 
    //获取自己数组 
    byte[] bs = readinputstream(inputstream); 
    response.setcontenttype("application/octet-stream;charset=iso8859-1");
    bufferedoutputstream output = null;
    bufferedinputstream input = null;
     try {
      output = new bufferedoutputstream(response.getoutputstream());
      // 中文文件名必须转码为 iso8859-1,否则为乱码
      string filenamedown = new string(filename.getbytes(), "iso8859-1");
      // 作为附件下载
      response.setheader("content-disposition", "attachment;filename=" + filenamedown);
  
      output.write(bs);
      response.flushbuffer();
     } catch (exception e) {
      log.error("download log file error", e);
     } // 用户可能取消了下载
     finally {
      if (input != null)
       try {
        input.close();
       } catch (ioexception e) {
        e.printstacktrace();
       }
      if (output != null)
       try {
        output.close();
       } catch (ioexception e) {
        e.printstacktrace();
       }
     }
   }
  } catch (exception e) {
   e.printstacktrace();
  }
 }
/** 
  * 从输入流中获取字节数组 
  * @param inputstream 
  * @return 
  * @throws ioexception 
  */ 
 public static byte[] readinputstream(inputstream inputstream) throws ioexception { 
  byte[] buffer = new byte[1024]; 
  int len = 0; 
  bytearrayoutputstream bos = new bytearrayoutputstream(); 
  while((len = inputstream.read(buffer)) != -1) { 
   bos.write(buffer, 0, len); 
  } 
  bos.close(); 
  return bos.tobytearray(); 
 } 

以上这篇java通过url下载文件并输出的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: