Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将android映像uri传递给异步任务的执行调用?_Java_Android_Image_Bitmap - Fatal编程技术网

Java 如何将android映像uri传递给异步任务的执行调用?

Java 如何将android映像uri传递给异步任务的执行调用?,java,android,image,bitmap,Java,Android,Image,Bitmap,我很难弄清楚如何传递图像的uri,因为我需要它来抓取文件,除非有其他方法,我就是看不到(我对这个很陌生)。我选择了图像,并将imageview的位图设置为位图,但现在尝试在单击“提交”按钮后将其发送到服务器 我知道我可以执行(uri);但是我如何从imageview中提取uri呢 代码如下:) 我努力工作的部分:) 私有类ImageUploadTask扩展了AsyncTask{ 我需要的是uri或文件。。。 字符串文件名=图像路径; 文件源文件=新文件(imagepath); 私有字符串webA

我很难弄清楚如何传递图像的uri,因为我需要它来抓取文件,除非有其他方法,我就是看不到(我对这个很陌生)。我选择了图像,并将imageview的位图设置为位图,但现在尝试在单击“提交”按钮后将其发送到服务器

我知道我可以执行(uri);但是我如何从imageview中提取uri呢

代码如下:)

我努力工作的部分:)

私有类ImageUploadTask扩展了AsyncTask{
我需要的是uri或文件。。。
字符串文件名=图像路径;
文件源文件=新文件(imagepath);
私有字符串webAddressToPost=”http://10.0.2.2/wardrobe";
HttpURLConnection conn=null;
DataOutputStream dos=null;
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024;
//私有进程对话框
private ProgressDialog ProgressDialog=新建ProgressDialog(
衣柜。这个);
@凌驾
受保护的void onPreExecute(){
progressDialog.setMessage(“上载…”);
progressDialog.show();
}
@凌驾
受保护的字符串doInBackground(无效…arg0){
如果(!sourceFile.isFile()){
progressDialog.disclose();
Log.e(“uploadFile”,“源文件不存在:“+imagepath”);
runOnUiThread(新的Runnable(){
公开募捐{
imageTextSelect.setText(“源文件不存在:”
+图像路径);
}
});
返回0;
}否则{
试一试{
//打开到Servlet的URL连接
FileInputStream FileInputStream=新FileInputStream(
源文件);
URL URL=新URL(upLoadServerUri);
//打开到URL的HTTP连接
conn=(HttpURLConnection)url.openConnection();
conn.setDoInput(true);//允许输入
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不要使用缓存副本
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“ENCTYPE”、“多部分/表单数据”);
conn.setRequestProperty(“内容类型”,
“多部分/表单数据;边界=”+边界);
conn.setRequestProperty(“上传的_文件”,文件名);
dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\”上载的文件\“文件名=\”
+文件名+“\”+lineEnd);
dos.writeBytes(lineEnd);
//创建最大大小的缓冲区
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
buffer=新字节[bufferSize];
//读取文件并将其写入表单。。。
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
而(字节读取>0){
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
}
//发送文件数据后所需的多部分表单数据。。。
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+两个连字符+行结束);
//来自服务器的响应(代码和消息)
serverResponseCode=conn.getResponseCode();
字符串serverResponseMessage=conn.getResponseMessage();
Log.i(“上传文件”,“HTTP响应为:”
+serverResponseMessage+“:”+serverResponseCode);
如果(服务器响应代码==200){
String msg=“文件上载已完成。\n\n请参阅此处上载的文件:\n\n”
+“F:/wamp/wamp/www/uploads”;
imageTextSelect.setText(msg);
Toast.makeText(衣橱.this,
“文件上载完成。”,Toast.LENGTH\u SHORT)
public class wardrobe extends Activity implements OnClickListener {

    // set variable for the fields
    private EditText nameField, sizeField, colorField, quantityField;
    private Spinner typeField, seasonField;
    private ImageView imageview;
    private ProgressBar progressBarField;
    private TextView imageTextSelect, resImage;
    private ProgressDialog progressDialog = null;
    private int serverResponseCode = 0;
    private Button uploadImageButton, postWardrobe;
    private String upLoadServerUri = null;
    private String imagepath = null;
    private Bitmap bitmap;

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

        // image upload stuff
        imageview = (ImageView) findViewById(R.id.user_photo);
        imageTextSelect = (TextView) findViewById(R.id.imageTextSelect);

        // button for upload image
        uploadImageButton = (Button) findViewById(R.id.uploadImageButton);

        // button for posting details
        postWardrobe = (Button) findViewById(R.id.postButton);

        uploadImageButton.setOnClickListener(this);
        postWardrobe.setOnClickListener(this);



    @Override
    public void onClick(View v) {

        /**
         * Opens dialog picker, so the user can select image from the gallery.
         * The result is returned in the method <code>onActivityResult()</code>
         */
        if (v == uploadImageButton) {
            // below allows you to open the phones gallery
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Complete action using"), 1);
        }
        if (v == postWardrobe) {

                // execute the post request

                new ImageUploadTask().execute();

            }
        }

    }

    /**
     * Retrives the result returned from selecting image, by invoking the method
     * <code>selectImageFromGallery()</code>
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 1 && null != data) {

            decodeUri(data.getData());
        }
    }

    public void decodeUri(Uri uri) {
        ParcelFileDescriptor parcelFD = null;
        try {
            parcelFD = getContentResolver().openFileDescriptor(uri, "r");
            FileDescriptor imageSource = parcelFD.getFileDescriptor();

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(imageSource, null, o);

            // the new size we want to scale to
            final int REQUIRED_SIZE = 1024;

            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);

            imageview.setImageBitmap(bitmap);

            // can take off below just shows path
            imageTextSelect.setText("select : " + uri);
        } catch (FileNotFoundException e) {
            // handle errors
        } catch (IOException e) {
            // handle errors
        } finally {
            if (parcelFD != null)
                try {
                    parcelFD.close();
                } catch (IOException e) {
                    // ignored
                }
        }
    }
    private class ImageUploadTask extends AsyncTask<Void, Void, String> {



What I need is the uri or the file...
String fileName = imagepath;
File sourceFile = new File(imagepath);


                private String webAddressToPost = "http://10.0.2.2/wardrobe";
                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;


                // private ProgressDialog dialog
                private ProgressDialog progressDialog = new ProgressDialog(
                                wardrobe.this);

                @Override
                protected void onPreExecute() {
                        progressDialog.setMessage("Uploading...");
                        progressDialog.show();
                }

                @Override
                protected String doInBackground(Void... arg0) {



if (!sourceFile.isFile()) {

                        progressDialog.dismiss();

                        Log.e("uploadFile", "Source File not exist :" + imagepath);

                        runOnUiThread(new Runnable() {
                                public void run() {
                                        imageTextSelect.setText("Source File not exist :"
                                                        + imagepath);
                                }
                        });

                        return 0;

                } else {
                        try {

                                // open a URL connection to the Servlet
                                FileInputStream fileInputStream = new FileInputStream(
                                                sourceFile);
                                URL url = new URL(upLoadServerUri);

                                // Open a HTTP connection to the URL
                                conn = (HttpURLConnection) url.openConnection();
                                conn.setDoInput(true); // Allow Inputs
                                conn.setDoOutput(true); // Allow Outputs
                                conn.setUseCaches(false); // Don't use a Cached Copy
                                conn.setRequestMethod("POST");
                                conn.setRequestProperty("Connection", "Keep-Alive");
                                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                                conn.setRequestProperty("Content-Type",
                                                "multipart/form-data;boundary=" + boundary);
                                conn.setRequestProperty("uploaded_file", fileName);

                                dos = new DataOutputStream(conn.getOutputStream());

                                dos.writeBytes(twoHyphens + boundary + lineEnd);
                                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                                + fileName + "\"" + lineEnd);

                                dos.writeBytes(lineEnd);

                                // create a buffer of maximum size
                                bytesAvailable = fileInputStream.available();

                                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                buffer = new byte[bufferSize];

                                // read file and write it into form...
                                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                while (bytesRead > 0) {

                                        dos.write(buffer, 0, bufferSize);
                                        bytesAvailable = fileInputStream.available();
                                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                }

                                // send multipart form data necesssary after file data...
                                dos.writeBytes(lineEnd);
                                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                                // Responses from the server (code and message)
                                serverResponseCode = conn.getResponseCode();
                                String serverResponseMessage = conn.getResponseMessage();

                                Log.i("uploadFile", "HTTP Response is : "
                                                + serverResponseMessage + ": " + serverResponseCode);

                                if (serverResponseCode == 200) {


                                                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                                                        + " F:/wamp/wamp/www/uploads";
                                                        imageTextSelect.setText(msg);
                                                        Toast.makeText(wardrobe.this,
                                                                        "File Upload Complete.", Toast.LENGTH_SHORT)
                                                                        .show();

                                }

                                // close the streams //
                                fileInputStream.close();
                                dos.flush();
                                dos.close();

                        } catch (MalformedURLException ex) {

                                progressDialog.dismiss();
                                ex.printStackTrace();


                                                imageTextSelect
                                                                .setText("MalformedURLException Exception : check script url.");
                                                Toast.makeText(wardrobe.this, "MalformedURLException",
                                                                Toast.LENGTH_SHORT).show();


                                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                        } catch (Exception e) {

                                progressDialog.dismiss();
                                e.printStackTrace();


                                                imageTextSelect.setText("Got Exception : see logcat ");
                                                Toast.makeText(wardrobe.this,
                                                                "Got Exception : see logcat ",
                                                                Toast.LENGTH_SHORT).show();

                                Log.e("Upload file to server Exception",
                                                "Exception : " + e.getMessage(), e);
                        }


}