91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java后臺Controller實現文件下載操作

發布時間:2020-10-16 17:56:32 來源:腳本之家 閱讀:312 作者:ywh22122 欄目:開發技術

代碼

參數:

1.filePath:文件的絕對路徑(d:\download\a.xlsx)

2.fileName(a.xlsx)

3.編碼格式(GBK)

4.response、request不介紹了,從控制器傳入的http對象

代碼片.

//控制器
@RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD)
public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception {
    boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request);
    if(is)
     System.out.println("成功");
    else
    System.out.println("失敗");  
}
//下載方法
public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){
   File f = new File(filePath);
    if (!f.exists()) {
      try {
        response.sendError(404, "File not found!");
      } catch (IOException e) {
        e.printStackTrace();
      }
      return false;
    }

    String type = fileName.substring(fileName.lastIndexOf(".") + 1);
    //判斷下載類型 xlsx 或 xls 現在只實現了xlsx、xls兩個類型的文件下載
    if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){
      response.setContentType("application/force-download;charset=UTF-8");
      final String userAgent = request.getHeader("USER-AGENT");
      try {
        if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE瀏覽器
          fileName = URLEncoder.encode(fileName, "UTF8");
        } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐瀏覽器
          fileName = new String(fileName.getBytes(), "ISO8859-1");
        } else {
          fileName = URLEncoder.encode(fileName, "UTF8");// 其他瀏覽器
        }
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
      } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
        return false;
      }
      InputStream in = null;
      OutputStream out = null;
      try {

        //獲取要下載的文件輸入流
        in = new FileInputStream(filePath);
        int len = 0;
        //創建數據緩沖區
        byte[] buffer = new byte[1024];
        //通過response對象獲取outputStream流
        out = response.getOutputStream();
        //將FileInputStream流寫入到buffer緩沖區
        while((len = in.read(buffer)) > 0) {
          //使用OutputStream將緩沖區的數據輸出到瀏覽器
          out.write(buffer,0,len);
        }
        //這一步走完,將文件傳入OutputStream中后,頁面就會彈出下載框

      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
      } finally {
        try {
          if (out != null)
            out.close();
          if(in!=null)
            in.close();
        } catch (IOException e) {
          logger.error(e.getMessage(), e);
        }
      }
      return true;
    }else {
      logger.error("不支持的下載類型!");
      return false;
    }
  }

實現效果

1.火狐瀏覽器效果

Java后臺Controller實現文件下載操作

2.chrome效果,自動下載

Java后臺Controller實現文件下載操作

補充知識:文件上傳/下載的幾種寫法(java后端)

文件上傳

1、框架已經幫你獲取到文件對象File了

  public boolean uploadFileToLocale(File uploadFile,String filePath) {
    boolean ret_bl = false;
    try {
      InputStream in = new FileInputStream(uploadFile);
      ret_bl=copyFile(in,filePath);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ret_bl;
  }  
  
  public boolean copyFile(InputStream in,String filePath) {
    boolean ret_bl = false;
    FileOutputStream os=null;
    try {
      os = new FileOutputStream(filePath,false);
      byte[] b = new byte[8 * 1024];
      int length = 0;
      while ((length = in.read(b)) > 0) {
        os.write(b, 0, length);
      }
      os.close();
      in.close();
      ret_bl = true;
    } catch (Exception e) {
      e.printStackTrace();
    }finally{   
        try {
          if(os!=null){
            os.close();
          }
          if(in!=null){
            in.close();
          }
          
        } catch (IOException e) {
          e.printStackTrace();
        }    
    }
    return ret_bl;
  }

}

2、天了個擼,SB架構師根本就飄在天空沒下來,根本就沒想文件上傳這一回事

public String uploadByHttp(HttpServletRequest request) throws Exception{
    String filePath=null;
    List<String> fileNames = new ArrayList<>();
    //創建一個通用的多部分解析器 
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 
      //判斷 request 是否有文件上傳,即多部分請求 
      if(multipartResolver.isMultipart(request)){
        //轉換成多部分request  
        MultipartHttpServletRequest multiRequest =multipartResolver.resolveMultipart(request); 
        MultiValueMap<String,MultipartFile> multiFileMap = multiRequest.getMultiFileMap();
        List<MultipartFile> fileSet = new LinkedList<>();
        for(Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()){
          fileSet = temp.getValue();
        }
        String rootPath=System.getProperty("user.dir");
        for(MultipartFile temp : fileSet){
          filePath=rootPath+"/tem/"+temp.getOriginalFilename();
          File file = new File(filePath);
          if(!file.exists()){
            file.mkdirs();
          }
          fileNames.add(temp.getOriginalFilename());
          temp.transferTo(file);
        }
      } 
  }

3、神啊,我正在擼框架,請問HttpServletRequest怎么獲取!!!!

(1)在web.xml中配置一個監聽

<listener>
    <listener-class>
      org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>

(2)HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

文件下載(直接用鏈接下載的不算),這比較簡單

1、本地文件下載(即文件保存在本地)

public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception {
    response.setCharacterEncoding("UTF-8");
    //設置ContentType字段值
    response.setContentType("text/html;charset=utf-8");
    //通知瀏覽器以下載的方式打開
    response.addHeader("Content-type", "appllication/octet-stream");
    response.addHeader("Content-Disposition", "attachment;filename="+fileName);
    //通知文件流讀取文件
    InputStream in = request.getServletContext().getResourceAsStream(filePath);
    //獲取response對象的輸出流
    OutputStream out = response.getOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    //循環取出流中的數據
    while((len = in.read(buffer)) != -1){
      out.write(buffer,0,len);
    }
  }

2、遠程文件下載(即網上資源下載,只知道文件URI)

public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){ 
     try {
         urlStr=urlStr.replaceAll("\\\\", "/"); 
        URL url = new URL(urlStr);  
        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();  
        
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
     response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1"));
        //獲取響應報文輸出流對象 
        //獲取response對象的輸出流
       OutputStream out = response.getOutputStream();
       byte[] buffer = new byte[1024];
       int len;
       //循環取出流中的數據
       while((len = in.read(buffer)) != -1){
          out.write(buffer,0,len);
       }
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }

以上這篇Java后臺Controller實現文件下載操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

睢宁县| 潞城市| 钟祥市| 苏尼特右旗| 东乌珠穆沁旗| 宁国市| 宁安市| 阿鲁科尔沁旗| 如皋市| 康乐县| 清流县| 安宁市| 黑龙江省| 子洲县| 高淳县| 明光市| 乐至县| 沙湾县| 乾安县| 龙游县| 漳州市| 苍南县| 舒城县| 苏尼特右旗| 黄山市| 长兴县| 东海县| 阿克苏市| 玉林市| 鄂州市| 侯马市| 娄烦县| 旬邑县| 九龙坡区| 察雅县| 湖南省| 凤山市| 嵩明县| 峨边| 修文县| 抚顺市|