Android拍照擷取照片路徑並上傳至伺服器+Servlet代碼

來源:互聯網
上載者:User

標籤:

先來用戶端代碼【這裡唯寫了主要代碼】

先來張,

iv_photo.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new ActionSheetDialog(SendGoodsDetailsActivity.this).builder().setTitle("上傳車輛照片").setCancelable(false).setCanceledOnTouchOutside(false).addSheetItem("拍照上傳", SheetItemColor.Blue, new OnSheetItemClickListener() {@Overridepublic void onClick(int which) {// 拍照//設定圖片的儲存路徑,作為全域變數imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/filename.jpg";File temp = new File(imageFilePath);Uri imageFileUri = Uri.fromFile(temp);//擷取檔案的Uri Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//跳轉到相機Activityit.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//告訴相機拍攝完畢輸出圖片到指定的Uri startActivityForResult(it, 102);}}).addSheetItem("相簿選擇", SheetItemColor.Blue, new OnSheetItemClickListener() {@Overridepublic void onClick(int which) {// 相簿選取Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");startActivityForResult(intent1, 103);}}).show();}});
@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {switch(requestCode){ case 102: if (resultCode == Activity.RESULT_OK) {  Bitmap bmp = BitmapFactory.decodeFile(imageFilePath);                  iv_photo.setImageBitmap(bmp); } break; case 103: Bitmap bm = null; // 外界的程式訪問ContentProvider所提供資料 可以通過ContentResolver介面 ContentResolver resolver = getContentResolver(); try {Uri originalUri = data.getData(); // 獲得圖片的uribm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 顯得到bitmap圖片// 這裡開始的第二部分,擷取圖片的路徑:String[] proj = { MediaStore.Images.Media.DATA };// 好像是android多媒體資料庫的封裝介面,具體的看Android文檔@SuppressWarnings("deprecation")Cursor cursor = managedQuery(originalUri, proj, null, null, null);// 按我個人理解 這個是獲得使用者選擇的圖片的索引值int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);// 將游標移至開頭 ,這個很重要,不小心很容易引起越界cursor.moveToFirst();// 最後根據索引值擷取圖片路徑String path = cursor.getString(column_index);iv_photo.setImageURI(originalUri); } catch (IOException e) {e.printStackTrace(); } break; }super.onActivityResult(requestCode,resultCode,data);}

下面是上傳的一個工具類,嘻嘻,從網上找的一個大神的,可以用

/** *  * 上傳工具類 * @author spring sky * Email:[email protected] * QQ:840950105 * MyName:石明政 */public class UploadUtil {    private static final String TAG = "uploadFile";    private static final int TIME_OUT = 10*1000;   //逾時時間    private static final String CHARSET = "utf-8"; //設定編碼    /**     * android上傳檔案到伺服器     * @param file  需要上傳的檔案     * @param RequestURL  請求的rul     * @return  返迴響應的內容     */    public static String uploadFile(File file,String RequestURL){        String result = null;        String  BOUNDARY =  UUID.randomUUID().toString();  //邊界標識   隨機產生        String PREFIX = "--" , LINE_END = "\r\n";         String CONTENT_TYPE = "multipart/form-data";   //內容類型                try {            URL url = new URL(RequestURL);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setReadTimeout(TIME_OUT);            conn.setConnectTimeout(TIME_OUT);            conn.setDoInput(true);  //允許輸入資料流            conn.setDoOutput(true); //允許輸出資料流            conn.setUseCaches(false);  //不允許使用緩衝            conn.setRequestMethod("POST");  //請求方式            conn.setRequestProperty("Charset", CHARSET);  //設定編碼            conn.setRequestProperty("connection", "keep-alive");               conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);             conn.connect();                        if(file!=null){                /**                 * 當檔案不為空白,把檔案封裝並且上傳                 */                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());                StringBuffer sb = new StringBuffer();                sb.append(PREFIX);                sb.append(BOUNDARY);                sb.append(LINE_END);                /**                 * 這裡重點注意:                 * name裡面的值為伺服器端需要key   只有這個key 才可以得到對應的檔案                 * filename是檔案的名字,包含尾碼名的   比如:abc.png                   */                                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);                 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);                sb.append(LINE_END);                dos.write(sb.toString().getBytes());                InputStream is = new FileInputStream(file);                byte[] bytes = new byte[1024];                int len = 0;                while((len=is.read(bytes))!=-1){                    dos.write(bytes, 0, len);                }                is.close();                dos.write(LINE_END.getBytes());                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();                dos.write(end_data);                dos.flush();                /**                 * 擷取響應碼  200=成功                 * 當響應成功,擷取響應的流                   */                int res = conn.getResponseCode();              if(res==200){                    InputStream input =  conn.getInputStream();                    StringBuffer sb1= new StringBuffer();                    int ss ;                    while((ss=input.read())!=-1){                        sb1.append((char)ss);                    }                    result = sb1.toString();                    System.out.println(result);            }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }}

在下就是調用上傳的方法了,這裡我給摘出來了

File file = new File(path); //這裡的path就是那個地址的全域變數String result = UploadUtil.uploadFile(file, RequestURL);

這裡用戶端就完成了,下面就是服務端代碼,這裡我用的是servlet

public class UploadShipServlet extends HttpServlet {private static final long serialVersionUID = 1L;private String path;public UploadShipServlet() {super();}public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();// 建立檔案項目工廠對象DiskFileItemFactory factory = new DiskFileItemFactory();// 設定檔案上傳路徑String upload = this.getServletContext().getRealPath("/");// 擷取系統預設的臨時檔案儲存路徑,該路徑為Tomcat根目錄下的temp檔案夾String temp = System.getProperty("java.io.tmpdir");// 設定緩衝區大小為 5Mfactory.setSizeThreshold(1024 * 1024 * 5);// 設定臨時檔案夾為tempfactory.setRepository(new File(temp));// 用工廠執行個體化上傳組件,ServletFileUpload 用來解析檔案上傳請求ServletFileUpload servletFileUpload = new ServletFileUpload(factory);// 解析結果放在List中try {List<FileItem> list = servletFileUpload.parseRequest(request);for (FileItem item : list) {String name = item.getFieldName();InputStream is = item.getInputStream();if (name.contains("content")) {System.out.println(inputStream2String(is));} else if (name.contains("img")) {try {path = upload+"\\"+item.getName();inputStream2File(is, path);break;} catch (Exception e) {e.printStackTrace();}}}out.write(path);  //這裡我把服務端成功後,返回給用戶端的是上傳成功後路徑} catch (FileUploadException e) {e.printStackTrace();System.out.println("failure");out.write("failure");}out.flush();out.close();}// 流轉化成字串public static String inputStream2String(InputStream is) throws IOException {ByteArrayOutputStream baos = new ByteArrayOutputStream();int i = -1;while ((i = is.read()) != -1) {baos.write(i);}return baos.toString();}// 流轉化成檔案public static void inputStream2File(InputStream is, String savePath) throws Exception {System.out.println("檔案儲存路徑為:" + savePath);File file = new File(savePath);InputStream inputSteam = is;BufferedInputStream fis = new BufferedInputStream(inputSteam);FileOutputStream fos = new FileOutputStream(file);int f;while ((f = fis.read()) != -1) {fos.write(f);}fos.flush();fos.close();fis.close();inputSteam.close();}}

ok了,這樣就大功告成了,多整理以後好用得著。

Android拍照擷取照片路徑並上傳至伺服器+Servlet代碼

聯繫我們

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