其他分享
首页 > 其他分享> > 相册浏览上传服务

相册浏览上传服务

作者:互联网

1  权限

   基本的用户权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET" />

应用权限

<application
    android:allowBackup="true"
    android:usesCleartextTraffic="true"
    android:requestLegacyExternalStorage="true"   //没有此权限,则总是提示文件无法找到错误

2  绝对路径获取   

 /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath( final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

3  异步线程

//图片上传异步线程
    private class WxpPicTransferToServerTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPostExecute(String result) {
            //最终结果的显示
            //mTvProgress.setText(result);
            tx.setText(result);
        }

        @Override
        protected void onPreExecute() {
            //开始前的准备工作
            //mTvProgress.setText("loading...");
            tx.setText("loading .....");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            //显示进度
            // mPgBar.setProgress(values[0]);
            // mTvProgress.setText("loading..." + values[0] + "%");
            tx.setText("loading:"+String.valueOf(values[0])+"%");
        }

        @Override
        protected String doInBackground(String... params)
        {
            //这里params[0]和params[1]是execute传入的两个参数
            String filePath = params[0];
            String uploadUrl = params[1];

            //下面即手机端上传文件的代码
            String end = "\r\n";
            String twoHyphens = "--";
            String boundary = "******";
            try {
                URL url = new URL(uploadUrl);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url
                        .openConnection();
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setConnectTimeout(6 * 1000);
                httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                httpURLConnection.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);

                DataOutputStream dos = new DataOutputStream(httpURLConnection
                        .getOutputStream());
                dos.writeBytes(twoHyphens + boundary + end);
                dos
                        .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                                + filePath.substring(filePath.lastIndexOf("/") + 1)
                                + "\"" + end);
                dos.writeBytes(end);

                //获取文件总大小
                FileInputStream fis = new FileInputStream(filePath);
                long total = fis.available();
                byte[] buffer = new byte[8192]; // 8k
                int count = 0;
                int length = 0;
                while ((count = fis.read(buffer)) != -1) {
                    dos.write(buffer, 0, count);
                    //获取进度,调用publishProgress()
                    length += count;
                    publishProgress((int) ((length / (float) total) * 100));
                    //这里是测试时为了演示进度,休眠500毫秒,正常应去掉
                    //Thread.sleep(500);
                }
                fis.close();
                dos.writeBytes(end);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
                dos.flush();

                InputStream is = httpURLConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                @SuppressWarnings("unused")
                String result = br.readLine();
                dos.close();
                is.close();
                return "上传成功";
            } catch (Exception e)
            {
                e.printStackTrace();
                 return "上传失败"+e.toString();
            }

        }
    }
    //

    4   相册图片选取并上传

 String[] mPermissionList = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE};
    public static final int REQUEST_PICK_IMAGE = 11101;
    //文件上传异步类
    String STR_REQUESTURL="http://x.x.x.x/Default4.aspx";
    String mCurrentPhotoPath="";

    private ImageView mShowImg;
    private TextView  tx;
    private Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mShowImg = (ImageView) findViewById(R.id.imageView);
        tx = (TextView) findViewById(R.id.txt);
        bt=(Button) findViewById(R.id.button);

        mShowImg.setImageResource(R.mipmap.ic_launcher);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {               
                openPhotoAlbum();
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                if (grantResults.length > 0 && writeExternalStorage && readExternalStorage) {
                    getImage();
                } else {
                    Toast.makeText(this, "请设置必要权限", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    private void getImage() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    REQUEST_PICK_IMAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PICK_IMAGE:
                    if (data != null) {
                        String realPathFromUri=getRealFilePath(this,data.getData());
                        tx.setText(realPathFromUri);
                        //显示图片
                        mShowImg.setImageURI(data.getData());

                        //上传文件
                        WxpPicTransferToServerTask mTask = new WxpPicTransferToServerTask();
                        mTask.execute(realPathFromUri, STR_REQUESTURL);

                        Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(this, "图片损坏,请重新选择", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }

    //
    //打开相册
    public void openPhotoAlbum() {
        ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
    }

5  ASPX服务器端保存代码

其他复杂的都是错误的,核心功能一行代码搞定

protected void Page_Load(object sender, EventArgs e)
    {
        string FileSaveDisk = "D:\\phpstudy_pro\\WWW\\WebSite2\\WxpPic";
        string imgFile = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
        string filePath = FileSaveDisk + "\\" + imgFile;

        //测试代码
        if (!IsPostBack)
        {           
            if (this.Request.Files.Count > 0)
            {
                HttpPostedFile file = this.Request.Files.Get(0);
                try
                {
                    file.SaveAs(filePath);
                    Response.Write("success");
                }
                catch
                {
                    Response.Write("error");
                }
            }

        }
        return;
   }

标签:String,相册,浏览,上传,void,new,null,data,httpURLConnection
来源: https://blog.csdn.net/sichuanpb/article/details/120645322