Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

android - Creating file from Uri

I'm trying to upload a image to php, for that I need to send a File to the server. So I am trying to create a file from the data parameter.

But I got this error Cannot resolve constructor File

Here's my code:

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
            // Get the url from data
            Uri selectedImageUri = data.getData();
            if (null != selectedImageUri) {
                // File
                File imageFilePath = new File(selectedImageUri);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The appropriate way is to getContentResolver().openInputStream(uri_of_your_file); and using a FileOutputStream to your desired path and then use that file.

As from Commonsware answer

You can use ContentResolver and openInputStream() to get an InputStream on the content represented by the Uri. You can create a FileOutputStream on some file that you control. And, you can use Java I/O to copy from the InputStream to the OutputStream, making your own copy of the content in a file that you control.

Sample code for doing that,

InputStream in =  getContentResolver().openInputStream("your_uri_here");
OutputStream out = new FileOutputStream(new File("your_file_here"));
        byte[] buf = new byte[1024];
        int len;
        while((len=in.read(buf))>0){
            out.write(buf,0,len);
        }
        out.close();
        in.close();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

56.9k users

...