HttpURLConnection上傳檔案(圖片)小試

來源:互聯網
上載者:User

需求:用HttpURLConnection類比上傳圖片並把圖片的名稱也要傳遞過去.

簡單分析:寫入流的時候依次寫入 圖片名稱 + "|" 分隔字元 +  圖片流

然後伺服器接收的再處理流.分別取出圖片名和圖片.

/**     * 上傳方法     * 返回上傳完畢的檔案名稱     * *     */    public String upload(File f)    {        try        {            //伺服器IP(這裡是從屬性檔案中讀取出來的)            String hostip = FileSupport.getServerIP();            URL url = new URL("http://"+ hostip +"/oxServer/ReceiveServlet");                        HttpURLConnection uc = (HttpURLConnection) url.openConnection();            //上傳圖片的一些參數設定            uc                    .setRequestProperty(                            "Accept",                            "image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");            uc.setRequestProperty("Accept-Language", "zh-cn");            uc                    .setRequestProperty("Content-type",                            "multipart/form-data;   boundary=---------------------------7d318fd100112");            uc.setRequestProperty("Accept-Encoding", "gzip,   deflate");            uc                    .setRequestProperty("User-Agent",                            "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");            uc.setRequestProperty("Connection", "Keep-Alive");            uc.setDoOutput(true);            uc.setUseCaches(true);                    //讀取檔案流            int size = (int) f.length();            byte[] data = new byte[size];            FileInputStream fis = new FileInputStream(f);            OutputStream out = uc.getOutputStream();            fis.read(data, 0, size);            //寫入檔案名稱            out.write(f.getName().trim().getBytes());            //寫入分隔字元            out.write('|');            //寫入圖片流            out.write(data);            out.flush();            out.close();            fis.close();                        //讀取響應資料            int code = uc.getResponseCode();            String sCurrentLine = "";            //存放響應結果            String sTotalString = "";            if (code == 200)            {                java.io.InputStream is = uc.getInputStream();                BufferedReader reader = new BufferedReader(                        new InputStreamReader(is));                while ((sCurrentLine = reader.readLine()) != null)                    if (sCurrentLine.length() > 0)                        sTotalString = sTotalString + sCurrentLine.trim();            }            else            {                sTotalString = "遠程伺服器串連失敗,錯誤碼:" + code;            }            return sTotalString;        }        catch (Exception e)        {            e.printStackTrace();        }        return null;    }

伺服器Servlet:

public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException    {        ServletInputStream inStream = request.getInputStream(); // 取HTTP請求流        int size = request.getContentLength(); // 取HTTP請求流長度        byte[] buffer = new byte[size]; // 用於緩衝每次讀取的資料        byte[] result = new byte[size]; // 用於存放結果的數組        int count = 0;        int rbyte = 0;        // 迴圈讀取        while (count < size)        {            rbyte = inStream.read(buffer); // 每次實際讀取長度存於rbyte中 sflj            for (int i = 0; i < rbyte; i++)            {                result[count + i] = buffer[i];            }            count += rbyte;        }        // 先找到檔案名稱和圖片流的標誌位'|'        int index = 0;        for (int i = 0; i < result.length; i++)        {            byte b = result[i];            if (b == '|')            {                index = i;                break;            }        }        // 存放檔案名稱        byte name[] = new byte[index + 1];        // 存放圖片位元組        byte[] img = new byte[size - index];        for (int i = 0; i < result.length; i++)        {            if (i < index)            {                name[i] = result[i];            }            if (i > index)            {                // 這時注意img數組的index要從0開始                img[i - index - 1] = result[i];            }        }        // 還原檔案名稱        String fileName = new String(name);        inStream.close();        String newFileName = renameFile(fileName);        // 響應用戶端        response.setContentType("text/html");        // 注意響應中文資料時要設定        response.setCharacterEncoding("GBK");        PrintWriter out = response.getWriter();        //可能情況 0 資料庫無相關記錄 1 檔案名稱不符合要求 其它情況為正常        if(newFileName.equals("0"))        {            out.write("0|" + fileName);        }        else if(newFileName.equals("1"))        {            out.write("1|" + fileName);        }        else        {            out.write(fileName);        }        out.close();        //上傳錯誤中止後續操作        if(newFileName.length()<= 1)        {            return;        }                File f = new File(ImageSupport.getOriginal() + "/" + newFileName);        FileOutputStream fos = new FileOutputStream(f);        fos.write(img);        fos.flush();        fos.close();        // 改變圖片大小後重新放置到新地點        ImageSupport.changeImageSize(f, ImageSupport.getAfter() + "/"                + newFileName, 300, 300);    }

我寫的是一個批量上傳圖片的程式,經測試通過.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.