1. 程式人生 > >HttpUrlConnection上傳圖片程式碼實現

HttpUrlConnection上傳圖片程式碼實現

/* 上傳檔案至Server的方法 */
  private void uploadFile() {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    String newName = "image.jpg";
    String uploadFile = "storage/sdcard1/bagPictures/102.jpg";
    ;
    String actionUrl = "http://192.168.1.123:8080/upload/servlet/UploadServlet"
; try { URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); /* 允許Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 設定傳送的method=POST */ con.setRequestMethod("POST"
); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 設定DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"file1\";filename=\"" + newName + "\"" + end); ds.writeBytes(end); /* 取得檔案的FileInputStream */ FileInputStream fStream = new FileInputStream(uploadFile); /* 設定每次寫入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 從檔案讀取資料至緩衝區 */ while ((length = fStream.read(buffer)) != -1) { /* 將資料寫入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); /* 取得Response內容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } /* 將Response顯示於Dialog */ showDialog("上傳成功" + b.toString().trim()); /* 關閉DataOutputStream */ ds.close(); } catch (Exception e) { showDialog("上傳失敗" + e); } }

伺服器端接收部分

public class UploadServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      System.out.println("IP:" + request.getRemoteAddr());
      // 1、建立工廠類:DiskFileItemFactory
      DiskFileItemFactory facotry = new DiskFileItemFactory();
      String tempDir = getServletContext().getRealPath("/WEB-INF/temp");
      facotry.setRepository(new File(tempDir));//設定臨時檔案存放目錄
      // 2、建立核心解析類:ServletFileUpload
      ServletFileUpload upload = new ServletFileUpload(facotry);
      upload.setHeaderEncoding("UTF-8");// 解決上傳的檔名亂碼
      upload.setFileSizeMax(1024 * 1024 * 1024);// 單個檔案上傳最大值是1M
      upload.setSizeMax(2048 * 1024 * 1024);//檔案上傳的總大小限制

      // 3、判斷使用者的表單提交方式是不是multipart/form-data
      boolean bb = upload.isMultipartContent(request);
      if (!bb) {
        return;
      }
      // 4、是:解析request物件的正文內容List<FileItem>
      List<FileItem> items = upload.parseRequest(request);
      String storePath = getServletContext().getRealPath(
          "/WEB-INF/upload");// 上傳的檔案的存放目錄
      for (FileItem item : items) {
        if (item.isFormField()) {
          // 5、判斷是否是普通表單:列印看看
          String fieldName = item.getFieldName();// 請求引數名
          String fieldValue = item.getString("UTF-8");// 請求引數值
          System.out.println(fieldName + "=" + fieldValue);
        } else {
          // 6、上傳表單:得到輸入流,處理上傳:儲存到伺服器的某個目錄中,儲存時的檔名是啥?
          String fileName = item.getName();// 得到上傳檔案的名稱 C:\Documents
                            // and
                            // Settings\shc\桌面\a.txt
                            // a.txt
          //解決使用者沒有選擇檔案上傳的情況
          if(fileName==null||fileName.trim().equals("")){
            continue;
          }
          fileName = fileName
              .substring(fileName.lastIndexOf("\\") + 1);
          String newFileName = UUIDUtil.getUUID() + "_" + fileName;
          System.out.println("上傳的檔名是:" + fileName);
          InputStream in = item.getInputStream();
          String savePath = makeDir(storePath, fileName) + "\\"
              + newFileName;
          OutputStream out = new FileOutputStream(savePath);
          byte b[] = new byte[1024];
          int len = -1;
          while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
          }
          in.close();
          out.close();
          item.delete();//刪除臨時檔案
        }
      }
    }catch(FileUploadBase.FileSizeLimitExceededException e){
      request.setAttribute("message", "單個檔案大小不能超出5M");
      request.getRequestDispatcher("/message.jsp").forward(request,
          response);
    }catch(FileUploadBase.SizeLimitExceededException e){
      request.setAttribute("message", "總檔案大小不能超出7M");
      request.getRequestDispatcher("/message.jsp").forward(request,
          response);
  }catch (Exception e) {
      e.printStackTrace();
      request.setAttribute("message", "上傳失敗");
      request.getRequestDispatcher("/message.jsp").forward(request,
          response);
    }
  }

  // WEB-INF/upload/1/3 打散儲存目錄
  private String makeDir(String storePath, String fileName) {
    int hashCode = fileName.hashCode();// 得到檔名的hashcode碼
    int dir1 = hashCode & 0xf;// 取hashCode的低4位 0~15
    int dir2 = (hashCode & 0xf0) >> 4;// 取hashCode的高4位 0~15
    String path = storePath + "\\" + dir1 + "\\" + dir2;
    File file = new File(path);
    if (!file.exists())
      file.mkdirs();
    System.out.println("儲存路徑是"+path);
    return path;
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

}

相關推薦

HttpUrlConnection圖片程式碼實現

/* 上傳檔案至Server的方法 */ private void uploadFile() { String end = "\r\n"; String twoHyphens = "--"; String boundary = "**

3種圖片實現預覽的方法

load app chunks isp 賦值 response with span attr 在常見的用戶註冊頁面,需要用戶在本地選擇一張圖片作為頭像,並同時預覽。 常見的思路有兩種:一是將圖片上傳至服務器的臨時文件夾中,並返回該圖片的url,然後渲染在html頁面;另一種

圖片功能實現

1.如果沒有相機許可權,申請開啟相機許可權 if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)){ ActivityCompat.requestPe

input file 方式圖片實現實時預覽

用普通的html的 <input type="file"/> 標籤是不能實現實時預覽功能的,獲取表單的值可以得到圖片所在路徑:C:\fakepath\test.png,如果將它直接賦值給img標籤的href屬性,會報錯:Not allowed to load lo

Java圖片程式碼事例

controller層實現: @RequestMapping("/createad")     public ModelAndView createAD(HttpServletRequest request, AdvertiseDTO dto, MultipartHttpS

ajax非同步圖片程式碼案例

html程式碼如下: <div class="form-group" style="width:60%;">             <table class="table">             <thead>          

jfinal中使用百度編輯器圖片實現

1、首先需要把flash工具放入到專案中,。 2、然後在頁面中寫上: <input id="curCount" name="curCount" type="hidden" value="0" /> 加上匯入圖片的外掛: <object id="flash"

TP框架一張圖片和批量圖片程式碼

上傳一張圖片 前端程式碼: <form action="{地址}" method="POST" enctype="multipart/form-data"> <input

解決使用jquery圖片實現回顯失敗,提示ReferenceError: $ is not defined

使用jquery上傳圖片並實現回顯 <scripttype="text/javascript"> //上傳 (非同步) functionuploadPic(){ //本次 jquery.form.js varoptions = {             

KindEditor富文本框編輯器圖片功能實現,基於java項目

ger char 大小 append 參考 java ont area reat 1. HTML標簽與jquery代碼 <textarea id="editor_id" style="width: 200px; height: 200px;"></text

springmvc和layui富文字編輯器實時圖片功能實現

本文將介紹 springmvc 上傳功能實現,以及layui 前端外掛的使用,尤其是其富文字編輯器的上傳圖片介面的實現。 一、開發準備 1、layui 官網:http://www.layui.com/ 點選"立即下載"可以獲取前端框架,沒有使用過的朋友可以自行了解下。 下載

springmvc處理圖片程式碼(校驗圖片尺寸、圖片大小)

package com.maizuo.web.controller; import com.maizuo.domain.Result; import com.maizuo.util.ConstantsConfig; import com.maizuo.util.Uploa

Android 自己封裝HttpUrlConnection圖片和欄位

/** * Created by hui on 2017/5/8. */ import android.util.Log; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; imp

自定義圖片按鈕 實現圖片的預覽和切換

功能:自定義上傳按鈕的樣式,初始樣式的透明度為0,設定自己想要的樣式,同時可以實現上傳圖片的預覽。 HTML程式碼: <form action="" name="formx" method="post" enctype="multipart/form-data

UEditor圖片到七牛C#(後端實現

nco nag manage ora 個人 finall code 七牛存儲 json 由於個人網站空間存儲有所以選擇將圖片統一存儲到七牛上,理由很簡單 1 免費10G 的容量 ,對個人網站足夠用 2 規範的開發者文檔 和完善的sdk(幾乎所有熱門語言sdk)

ckeditor添加自定義按鈕整合swfupload實現批量圖片

下載 了解 nbsp 文件 mouseover 去掉 dial size pro ckeditor添加自定義按鈕整合swfupload實現批量上傳圖片給ckeditor添加自定義按鈕,由於ckeditor只能上傳一張圖片,如果要上傳多張圖片就要結合ckfinder,而ckf

基於Jquery插件Uploadify實現實時顯示進度條圖片

準備 深入學習 pla 回調 true bar put and 分割 網址:http://www.jb51.net/article/83811.htm 這篇文章主要介紹了基於Jquery插件Uploadify實現實時顯示進度條上傳圖片的相關資料,感興趣的小夥伴們可

C# Asp.net使用FormData對象實現ajax提交表單及圖片

sync ext syn data .... error post req 序列化 1、html代碼: <form id="postForm"> 文件名:<input type="text" name="filename" />

Ueditor結合七牛雲存儲圖片、附件和圖片在線管理的實現和最新更新

1.4 star json serve 列出文件 教程 開發 存儲服務器 name 最新下載地址: https://github.com/widuu/qiniu_ueditor_1.4.3 Ueditor七牛雲存儲版本 註意事項 老版本請查看 : https://gith

前端實現input[type='file']圖片預覽效果

query selector indexof 圖片加載 code lock 復用 lec 應用 眾所周知JavaScript在設計上處於安全角度考慮,是不允許讀寫本地文件的(原因請自行百度); 但是在實際項目應用中,經常會使用到上傳圖片,並且可以讓用戶直接預覽圖片。對於此種