圖片上傳利用request.getInputStream()擷取檔案流時遇到的問題,

來源:互聯網
上載者:User

圖片上傳利用request.getInputStream()擷取檔案流時遇到的問題,

圖片上傳功能是我們web裡面經常用到的,獲得的方式也有很多種,這裡我用的是request.getInputStream()擷取檔案流的方式。想要擷取檔案流有兩種方式,附上代碼

int length = request.getContentLength();//擷取請求參數長度。byte[] bytes = new byte[length];//定義數組,長度為請求參數的長度DataInputStream dis = new DataInputStream(request.getInputStream);//擷取請求內容,轉成資料輸入流int readcount = 0;//定義輸入資料流讀取數while(readcount < length){    int aa= dis.read(bytes,readcount,length);    //讀取輸入資料流,放入bytes數組,返回每次讀取的數量    readcount = aa + readcount; //下一次的讀取開始從readcount開始}//讀完之後bytes就是輸入資料流的位元組數組,將其轉為字串就能看到String bb = new String(bytes,"UTF-8");

上面這種是利用讀取輸入資料流的方式,也可以用寫入位元組輸入資料流的方式擷取,就不需要擷取請求長度了

DataInputStream dis = new DataInputStream(request.getInputStream());ByteArrayOutputStream baot = new ByteArrayOutputStream();byte[] bytes = new byte[1024]; //定義一個數組 用來讀取int n = 0;//每次讀取輸入資料流的量while((n=dis.read(bytes))!=-1){    baot.write(bytes);  //將讀取的位元組流寫入位元組輸出資料流  }byte[] outbyte = boat.toByteArray();//將位元組輸出資料流轉為自己數組。String bb = new String(outbyte,"UTF-8");

這兩種方式都能擷取傳輸的內容,但有兩點一定要注意一下,最開始在擷取的時候只能擷取到檔案的名字卻沒有檔案的內容,這裡附上測試用的前端代碼:

上網查了一下,有的人是input標籤裡面沒有name屬性會導致這個問題,但是我並不是沒有name標籤。繼續查是這樣的:

所以我覺得肯定是缺少了發送類型所以在form標籤中加入了enctype='multipart/form-data',果然可以擷取內容了。

然後就是第二個問題,也是我們通過request.getInputStream()方法擷取檔案的話,擷取的內容不只是只有檔案的,即使你表單中只有一個file標籤。剛開始我就是犯了這個錯誤,用拿到的byte數組直接輸入或者轉成檔案都是顯示不出來,後來才意識到,拿到了inputStream的bytes還要把檔案的內容從中剝離出來才可以。這裡提供一個方法,具體實現過程還沒有細研究,先附上之後再細看

/**     * 取得圖片資料     *     * @param requestData     * @param contentType     * @return     * @throws IOException     */    private byte[] getImgData(byte[] requestData, String contentType)            throws IOException {        String txtBody = new String(requestData, "GBK");        if (!txtBody.contains("image/jpg") && !txtBody.contains("image/jpeg")&& !txtBody.contains("jpg")) {            return null;        }        String boundarytext = contentType.substring(                contentType.lastIndexOf("=") + 1, contentType.length());        // 取得實際上傳檔案的起始與結束位置        int pos = txtBody.indexOf("filename=\"");        pos = txtBody.indexOf("\n", pos) + 1;        pos = txtBody.indexOf("\n", pos) + 1;        pos = txtBody.indexOf("\n", pos) + 1;        // 檔案描述資訊後就檔案內容,直到為檔案邊界為止,從pos開始找邊界        int boundaryLoc = txtBody.indexOf(boundarytext, pos) - 4;        ByteArrayOutputStream realdatas = null;        try {            int begin = ((txtBody.substring(0, pos)).getBytes("GBK")).length;            int end = ((txtBody.substring(begin, boundaryLoc)).getBytes("GBK")).length;            realdatas = new ByteArrayOutputStream();            realdatas.write(requestData, begin, end);             return realdatas.toByteArray();        } finally {            if (null != realdatas) {                try {                    realdatas.close();                } catch (IOException e) {                    logger.error("處理上傳圖片資料錯誤:", e);                }            }        }    }

這裡的參數就是請求的內容數組bytes以及請求類型,類型的話我們可以通過request.getContentType()方法直接擷取,傳回值同樣是byte數組,返回的byte數組就是我們上傳圖片的內容了。

返回前端的話,直接利用response就可以。

OutputStream os = response.getOutputStream();os.write(bytes);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.