图片拍照上传和相册选取

来源:互联网 发布:知乎句子孤独 编辑:程序博客网 时间:2024/04/30 11:53
拍照上传和本地上传实现:
Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(it, 1); 

Intent intent = new Intent();  
                intent.setType("image/*");  
                intent.setAction(Intent.ACTION_GET_CONTENT);  
                startActivityForResult(intent, 2); 

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Log.d("TAG", "onActivityResult");

            switch(requestCode) {  
            case 1:  
                Log.d("TAG", "camera");
                Uri uri1 = data.getData();
                Bitmap b = null;
                if(uri1!=null){
                    b = BitmapFactory.decodeFile(uri1.getPath());
                }else{
                    Bundle extras = data.getExtras();
                    if(extras!=null){
                        b = (Bitmap) extras.get("data");
                    }else{
                        Toast.makeText(this, "获取图片失败!", Toast.LENGTH_LONG).show();
                        return;
                    }
                }

            mImageView.setImageBitmap(b);  
            //将Bitmap保存至SD卡
            //开启异步任务,上传至服务器
                break;  
            case 2: 
                Log.d("TAG", "pictrue");
                Uri uri = data.getData(); 
                Log.d("TAG", "uri: " + uri);
                mImageView.setImageURI(uri);
                ContentResolver cr = this.getContentResolver();  
                Cursor c = cr.query(uri, null, null, null, null);  
                c.moveToFirst();  
                String photoTemp = c.getString(c.getColumnIndex("_data"));  
                Log.d("TAG", "photoTemp: " + photoTemp);
            //开启异步任务,上传至服务器
                break;  
            default:  
                break;  
            };  
        }
    }
--------------------------------------------------------------------------------------------------
文件上传客户端实现:
/* 上传文件至Server的方法 */  
    private void uploadFile()  
    {  

        String uploadUrl = "http://192.168.8.40:8080/JavaWebTest/upload";  
        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.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=\""  
                    + srcPath.substring(srcPath.lastIndexOf("/") + 1)  
                    + "\"" + end);  
            dos.writeBytes(end);  

            FileInputStream fis = new FileInputStream(srcPath);  
            byte[] buffer = new byte[8192]; // 8k  
            int count = 0;  
            while ((count = fis.read(buffer)) != -1)  
            {  
                dos.write(buffer, 0, count);  

            }  
            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);  
            String result = br.readLine();  

            Toast.makeText(this, result, Toast.LENGTH_LONG).show();  
            dos.close();  
            is.close();  

        } catch (Exception e)  
        {  
            e.printStackTrace();  
            setTitle(e.getMessage());  
        }  

    }  
------------------------------------------------------------------------------------------------------
文件上传服务端实现:
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try  
        {  
            request.setCharacterEncoding("UTF-8"); // 设置处理请求参数的编码格式  
            response.setContentType("text/html;charset=UTF-8"); // 设置Content-Type字段值  
            PrintWriter out = response.getWriter();  

            // 下面的代码开始使用Commons-UploadFile组件处理上传的文件数据  
            FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory对象  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            // 分析请求,并得到上传文件的FileItem对象  
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);  
            // 从web.xml文件中的参数中得到上传文件的路径  
            String uploadPath = request.getSession().getServletContext().getRealPath("/images/");  
            System.out.println("uploadPath: " +uploadPath);
            File file = new File(uploadPath);  
            if (!file.exists())  
            {  
                file.mkdir();  
            }  
            String filename = ""; // 上传文件保存到服务器的文件名  
            InputStream is = null; // 当前上传文件的InputStream对象  
            // 循环处理上传文件  
            for (FileItem item : items)  
            {  
                // 处理普通的表单域  
                if (item.isFormField())  
                {  
                    if (item.getFieldName().equals("filename"))  
                    {  
                        // 如果新文件不为空,将其保存在filename中  
                        if (!item.getString().equals(""))  
                            filename = item.getString("UTF-8"); 
                        System.out.println("filename:    -------" + filename);
                    }  
                }  
                // 处理上传文件  
                else if (item.getName() != null && !item.getName().equals(""))  
                {  
                    // 从客户端发送过来的上传文件路径中截取文件名  
                    filename = item.getName().substring(  
                            item.getName().lastIndexOf("\\") + 1);  
                    System.out.println("filename:    +++++++++++" + filename);
                    is = item.getInputStream(); // 得到上传文件的InputStream对象  
                }  
            }  
            // 将路径和上传文件名组合成完整的服务端路径  
            filename = uploadPath + "\\" + filename; 
            System.out.println("filename:==========" + filename);
            // 如果服务器已经存在和上传文件同名的文件,则输出提示信息  
            if (new File(filename).exists())  
            {  
                new File(filename).delete();  
            }  
            // 开始上传文件  
            if (!filename.equals(""))  
            {  
                // 用FileOutputStream打开服务端的上传文件  
                FileOutputStream fos = new FileOutputStream(filename);  
                byte[] buffer = new byte[8192]; // 每次读8K字节  
                int count = 0;  
                // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中  
                while ((count = is.read(buffer)) > 0)  
                {  
                    fos.write(buffer, 0, count); // 向服务端文件写入字节流  

                }  
                fos.flush();
                fos.close(); // 关闭FileOutputStream对象  
                is.close(); // InputStream对象  
                out.println("文件上传成功!");  
                out.flush();
                out.close();
            }
            // 将图片的url更新至数据表
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();
        }  
    }
0 0
原创粉丝点击