1. 程式人生 > >web版使用者通過瀏覽器下載圖片java後臺程式碼

web版使用者通過瀏覽器下載圖片java後臺程式碼

/**
     * web版使用者通過瀏覽器下載圖片
     */
    @RequestMapping(value = "webDownloadImg/{imgId}", method = RequestMethod.GET)
    public @ResponseBody
    void webDownloadImg(@PathVariable String imgId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*
        Map<String, Object> map = super.getParamsMap(json);
        String imgpath = map.get("imgpath").toString();
        imgpath = imgpath.substring(1,imgpath.length());*/
        // 獲取圖片絕對路徑
        String path = request.getSession().getServletContext().getRealPath("/");
        //獲取圖片的url
        PictureAblumImgDto pto = pictureAlbumService.getPictureUrl(imgId);
        if(pto != null){
            // 建立檔案輸入流
            FileInputStream is = null;
            // 響應輸出流
            ServletOutputStream out = null;
            String imgpath = pto.getImageUrl();
            try {
                File file = new File(path + imgpath);
                imgpath = imgpath.substring(1,imgpath.length());
                response.setContentType("application/octet-stream");
                //設定頭資訊,內容處理的方式,attachment以附件的形式開啟,就是進行下載,並設定下載檔案的命名
                response.setHeader("Content-Disposition","attachment;filename="+file.getName());
                is = new FileInputStream(file);
                out = response.getOutputStream();
                // 建立緩衝區
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                is.close();
                out.flush();
                out.close();
            } catch (Exception e) {
                logger.error("ERROR:" + e);
            }finally{
                is.close();
                out.flush();
                out.close();
            }
        }

    }

//前臺jquery請求方式

function reqByAjax(url, param, reqType, callback, isAsync) {
    if(iBrowser.android){//解決部分安卓手機獲取localStorage失敗問題。
        mylocalStorage = getStorage();//獲取localStorage
    }
    //設定預設值
    isAsync = (typeof(isAsync)=="undefined"||isAsync==="")?true:isAsync;
    var iAjax = $.ajax({
        url: "/"+url,
        type: reqType,
        dataType:"json",      
        contentType:"application/json",
        async:isAsync,
        data:JSON.stringify(param),
        beforeSend: function(request) {
           request.setRequestHeader("ticket", mylocalStorage.getItem("ticket") ? mylocalStorage.getItem("ticket"):"1s");
           //判斷裝置系統型別
           //request.setRequestHeader("osType", mylocalStorage.getItem("osType") ? mylocalStorage.getItem("osType"): 0);
           if(iBrowser.android){
               request.setRequestHeader("osType", "1");
              }else if(iBrowser.ios || iBrowser.iPhone || iBrowser.iPad){
                  request.setRequestHeader("osType", "2");
              }
           //設定guid
           request.setRequestHeader("guid", mylocalStorage.getItem("guid") ? mylocalStorage.getItem("guid"): 0);
        },
        success: function(data,textStatus) {
            if(data) {
                //ticket已過期執行登陸
                if(data.errorCode == 10003){
                    doLogin(url, param, reqType, callback, isAsync);
                }else{
                    if(callback) {
                        callback(data);
                    }
                }
            }
        },
        error: function() { //abort會執行error方法
            alert("親 網路不給力,再重新整理一下唄:)");
        }
    });
    //設定請求超時提醒,時間預設為20秒
    setTimeout(function() {
        if(iAjax && iAjax.readyState && iAjax.readyState != 4) //還在請求狀態時
        {
             iAjax.abort();
             alert("親 網路不給力,再重新整理一下唄:)");
        }
    }, 1000*parseInt(20));
}

//傳送請求

$("#w_download_id").html('<a href="/cs/webDownloadImg/'+download_img_albumId+'" style="text-align:center;"><img src="../images/download.png" style="width:26px;margin-top:11px;" onmousedown="userDownloadPicture()"/></a>');

相關推薦

web使用者通過瀏覽器下載圖片java後臺程式碼

/**      * web版使用者通過瀏覽器下載圖片      */     @RequestMapping(value = "webDownloadImg/{imgId}", method = RequestMethod.GET)     public @Respons

Java 通過url下載圖片

//web端通過點選下載圖片到本地(圖片url是服務上的訪問路徑) 前端程式碼: <a href ="javascript:void(0)"  onclick="downloadImg('${root}/web/${url}')" class="c-3277de m

通過瀏覽器下載服務器文件(日誌)

服務器文件 logs windows server 運行 科技 ron n) pytho 下載服務器的文件是經常需要進行的操作. 可以通過FTP工具進行(如Filezilla等). 以下提供一種通過瀏覽器下載服務器文件的黑科技: 1. 在windows/linux/sola

通過URL下載圖片進行壓縮並上傳到oss和本地

package test.com.redis; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStr

通過url下載圖片到本地

/** * 檔案或資料夾不存在則建立 * @param dir 資料夾 * @param filepath 檔名 */ public static void createDirFile(String dir){ File file = new File(dir); if(!fil

瀏覽器下載圖片

/** * 下載圖片 * @param request * @throws IOException */ @ResponseBody @RequestMapping("downLoad.do") public void downLoa

httpclient4下載圖片 java實現

有時候需要從網上抓取一下圖片jpg、png等,也可以抓取zip等,這樣就需要寫程式才能達到想要的效果, 下面是用httpclient4做一個工具類,非常的好用 package com.wamei.tool; import java.awt.image.BufferedIm

QT通過URL下載圖片

標頭檔案: #ifndef DOWNLOADER_H #define DOWNLOADER_H #include <QFile> #include <QNetworkAccessManager> #include <QNetworkReques

[unity3d]unity打包web後自定義載入圖片

/**********************************************************/ <script type="text/javascript"> var params = {

通過jna簡單實現java後臺監聽鍵盤觸發修改系統時間

      由於玩某網遊需要在出副本時等一分鐘,而修改系統時間+1分鐘可以提前出副本,避免麻煩寫了個java後臺監聽鍵盤觸發修改系統時間的指令碼,當按下設定好的鍵盤組合即呼叫修改函式。     修改時間的函式程式碼如下(呼叫CMD命令):

前臺通過base64傳圖片後臺的實現方法

前臺將圖片轉換為base64的方法如下: $("#article_image").change(function(){ var file = this.files[0]; //判斷型別是不是圖片 if(!/image\/\w+/.

jquery通過ajax-json訪問java後臺傳遞引數,通過request.getParameter獲取不到引數的說明

Java後臺伺服器是apache-tomcat-6.0.37 正常的post請求(不包括ajax請求)在http頭中的content-type為application/x-www-form-urlencoded,這時在java後臺可以通過request.getPara

Java後臺程式碼實現POI檔案的匯入匯出

前言 工作中常常會用到POI的匯入匯出功能,今天為大家詳細介紹一下平時用到的最多的匯入Excel表格資料和匯出資料為Excel表格的相關程式碼操作!本案例是SpringBoot專案,廢話不多說上程式碼! 1.Controller層程式碼 //相關導包 import

Echarts折線圖動態獲取資料例項(附java後臺程式碼

// 基於準備好的dom,初始化echarts例項 var myChart = echarts.init(document.getElementById('line')); // 指定圖表的配置項和資料 var option = {

APP 微信支付java後臺程式碼(解決支付失敗返回-1)

開發之前的準備工作: APP支付申請條件 申請成為APP支付商戶需要滿足以下條件: 2、APP應用必須通過開發者認證。 APP支付申請方法 1、登陸開放平臺(open.weixin.qq.com),選擇"管理中心"=》"移動應用",選擇需要申請支付的應用,點選"檢視

java後臺程式碼建立表格並填充相應的內容

       java後臺程式碼建立表格(生成圖片)                                             /**      * 動態建立5行兩列表格,並填充相應的內容      *      * @param       * @

java web 讀取數據庫數據寫入Excel返回瀏覽器下載

ade 瀏覽器 spa tchar download eat tno efault 寫入excel 1 @RequestMapping(value = "/download", method = RequestMethod.GET) 2 public voi

JAVA中建立HTTP通訊,從伺服器上獲取HTML程式碼通過HTTP請求來下載圖片或其他二進位制檔案的程式,下載結果要按下載到的檔案型別進行存檔中。

通過HTTP請求來下載圖片或其他二進位制檔案的程式,下載結果要按下載到的檔案型別進行存檔 將程式碼從伺服器的中獲取下來的程式碼,在我之前已經講過了這裡寫連結內容 這裡我們就直接將原始碼稍加改動,加入一個檔案並請將builder 寫入即可。 import

Java Web匯出excel表,瀏覽器下載匯出excel表

1 自定義註解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ExcelTable { String value() default ""; }

javaWEB專案如何防止瀏覽器直接開啟下載的檔案

 java的web專案防止瀏覽器直接開啟下載的檔案,在web.xml檔案中配置mime下載檔案型別就可以了,配置的示例: <mime-mapping> <extension>doc</extension> <mime-type&