Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android4.4 + WebAPI 實現拍照上傳,android4.4webapi

Android4.4 + WebAPI 實現拍照上傳,android4.4webapi

編輯:關於android開發

Android4.4 + WebAPI 實現拍照上傳,android4.4webapi


     網上有很多關於拍照上傳的實現方法,如果用新版本android去運行有可能會發現根本實現不了。主要原因是android從4.4版本開始通過intent.ACTION_GET_CONTENT打開選擇器後,getData()返回的URI沒有包含真實的文件路徑,而是像這樣“content://com.android.providers.media.documents/document/image:1234”,以至於用傳統的方式找不到圖片的路徑。最簡單的解決辦法是用intent.ACTION_PICK代替intent.ACTION_GET_CONTENT。下面給出4.4版本後拍照上傳的具體實現方法:

第一步:點擊拍照按鈕代碼

        //點擊拍照
        btnHeadCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent itCamera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(itCamera,0);
            }
        });

 

第二步:保存拍照圖片代碼

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 0://拍照
                savePhoto(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


   final String SAVE_PATH=Environment.getExternalStorageDirectory()+"/my_head.jpg"; //拍照後保存路徑 
//保存圖片
public void savePhoto(Intent it){ Bundle bundle=it.getExtras(); if(bundle!=null){ Bitmap photo = bundle.getParcelable("data"); imgHead.setImageBitmap(photo); File fileHead=new File(SAVE_PATH); try { if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ if(!fileHead.getParentFile().exists()){ fileHead.getParentFile().mkdir(); } BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(fileHead)); photo.compress(Bitmap.CompressFormat.JPEG,80,bos); bos.flush(); bos.close(); }else { Toast toast = Toast.makeText(HeadPhotoActivity.this, "保存失敗!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }


第三步:上傳圖片代碼

String SERVER_URL = Config.PhotoAPI+"/UploadImage";//上傳的服務端API地址

btnHeadCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread(new Runnable() { @Override public void run() { File file = new File(SAVE_PATH); Message msg = new Message(); msg.what = 0; if(file!=null) { try { int re = ImageUtils.uploadForm(file, SERVER_URL); msg.obj = re; } catch (IOException ex) { msg.obj = 0; Toast.makeText(HeadPhotoActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show(); } handler.sendMessage(msg); }else { Toast.makeText(HeadPhotoActivity.this, "找不到上傳圖片", Toast.LENGTH_SHORT).show(); } } }).start(); } });

 

final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        if ((int)msg.obj == 1) {
                            Toast.makeText(HeadPhotoActivity.this, "上傳成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(HeadPhotoActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }

            }
        };

 

    /**
     *
     * @param uploadFile
     *            需要上傳的文件
     * @param serverUrl
     *            上傳的服務器的路徑
     * @throws IOException
     */
    public static int uploadForm(File uploadFile,  String serverUrl)
            throws IOException {
        int re=0;

        String fileName = uploadFile.getName();
        StringBuilder sb = new StringBuilder();
        sb.append("--" + BOUNDARY + "\r\n");
        sb.append("Content-Disposition: form-data; name=\"" + fileName
                + "\"; filename=\"" + fileName + "\"" + "\r\n");
        sb.append("Content-Type: image/jpeg" + "\r\n");
        sb.append("\r\n");

        byte[] headerInfo = sb.toString().getBytes("UTF-8");
        byte[] endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
        System.out.println(sb.toString());
        URL url = new URL(serverUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + BOUNDARY);
        conn.setRequestProperty("Content-Length", String
                .valueOf(headerInfo.length + uploadFile.length()
                        + endInfo.length));
        conn.setDoOutput(true);

        OutputStream out = conn.getOutputStream();
        InputStream in = new FileInputStream(uploadFile);
        out.write(headerInfo);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) != -1)
            out.write(buf, 0, len);

        out.write(endInfo);
        in.close();
        out.close();
        if (conn.getResponseCode() == 200) {
            re=1;
        }
        return re;
    }

 

最後給出服務端WebAPI代碼:

        [HttpPost]
        public async Task<HttpResponseMessage> UploadImage()
        {
string filePath = "~\\UploadFiles\\Photo"; // 取得文件夾 string dir = HttpContext.Current.Server.MapPath(filePath); //如果不存在文件夾,就創建文件夾 if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var provider = new CustomMultipartFormDataStreamProvider(dir); try { // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); foreach (MultipartFileData file in provider.FileData) { //file.Headers.ContentDisposition.FileName;//上傳文件前的文件名 //file.LocalFileName;//上傳後的文件名 Photo p = new Photo(); p.ImgInfo = file.LocalFileName.Substring(file.LocalFileName.LastIndexOf("\\")); p.Sort = "員工相冊"; p.AddUser = "admin"; p.AddTime = DateTime.Now; p.Url = filePath + p.ImgInfo; db.Photo.Add(p); db.SaveChanges(); } return Request.CreateResponse(HttpStatusCode.OK);
} catch { return Request.CreateResponse(HttpStatusCode.BadRequest);
} }
    //重寫上傳文件名
    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider 
    {
        public CustomMultipartFormDataStreamProvider(string path)
            : base(path)
        { }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            return fileName + "_" + headers.ContentDisposition.FileName.Replace("\"", string.Empty);//base.GetLocalFileName(headers);
        }
    }

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved