如何将图像从android上传到FTP中的特定文件夹

时间:2014-01-18 06:55:42

标签: java android ftp

我从画廊中挑选一张图片并从相机中捕捉。当我点击上传按钮时,图像应该上传到FTP中的文件夹。有人可以帮帮我吗?

public class MainActivity extends Activity {

private final int SELECT_FILE = 1;
private final int REQUEST_CAMERA = 0;
private ImageView ivImage;
private Button btnSetImage;
private ProgressDialog dialog;
String fileExtension;
private Button upload;
ArrayList<String> paths = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ivImage = (ImageView) findViewById(R.id.ivImage);
    btnSetImage = (Button) findViewById(R.id.btnSelectPhoto);
    upload = (Button) findViewById(R.id.upload_btn);

    btnSetImage.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
    upload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

                dialog = ProgressDialog.show(MainActivity.this, "Uploading",
                        "Please wait...", true);
                dialog.setCancelable(true);
                 doFileUpload();

            }
    });

}

private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment
                        .getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, REQUEST_CAMERA);
            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select File"),
                        SELECT_FILE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }

        }
    });
    builder.show();
}
private void doFileUpload(){
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null; 
    String exsistingFileName = "/sdcard/six.3gp";
    // Is this the place are you doing something wrong.
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    String urlString = "http://192.168.1.5/upload.php";
    try
    {
        Log.e("MediaPlayer","Inside second Method");
        FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
        dos = new DataOutputStream( conn.getOutputStream() );
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
        dos.writeBytes(lineEnd);
        Log.e("MediaPlayer","Headers are written");
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        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);
        }
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
           // tv.append(inputLine);
        // close streams
        Log.e("MediaPlayer","File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    catch (MalformedURLException ex)
    {
        Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
        Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
    }

    //------------------ read the SERVER RESPONSE
    try {
        inStream = new DataInputStream ( conn.getInputStream() );
        String str;            
        while (( str = inStream.readLine()) != null)
        {
            Log.e("MediaPlayer","Server Response"+str);
        }
        /*while((str = inStream.readLine()) !=null ){

        }*/
        inStream.close();
    }
    catch (IOException ioex){
        Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
    }
}
/*class ImageUploadTask extends AsyncTask<Void, Void, String> {
    BufferedReader in = null;
    HttpEntity resEntity;
    String vdeoName;
    ArrayList<String> fileNames = new ArrayList<String>();
    String urlPosting;

    protected String doInBackground(Void... unsued) {
        //Log.d(TAG, "inside doin bg");
        int length = paths.size();
        //Log.d(TAG, "length" + length);
        //String title = caption.getText().toString();
        for (int i = 0; i < length; i++) {

            Log.i("INDEX", "################");
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://news5.in/api/upload");
                File file = new File(paths.get(i));
                String fName = file.getName();

                fileNames.add(fName);

                FileBody filebodyVideo = new FileBody(
                        new File(paths.get(i)));

                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("myFile", filebodyVideo);

                httppost.setEntity(reqEntity);

                // DEBUG
                System.out.println("executing request "
                        + httppost.getRequestLine());
                HttpResponse response = httpclient.execute(httppost);

                String res = Util.convertHttpResponseToString(response);
                fileExtension = res;

                //Log.d(TAG, "response" + res + "   " + i);

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

            }
        }*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            File f = new File(Environment.getExternalStorageDirectory()
                    .toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bm;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        btmapOptions);

                // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                ivImage.setImageBitmap(bm);

                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream fOut = null;
                File file = new File(path, String.valueOf(System
                        .currentTimeMillis()) + ".jpg");
                try {
                    fOut = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == SELECT_FILE) {
            Uri selectedImageUri = data.getData();

            String tempPath = getPath(selectedImageUri, MainActivity.this);
            Bitmap bm;
            BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
            bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
            ivImage.setImageBitmap(bm);
        }
    }
        //return urlPosting;
}

public String getPath(Uri uri, Activity activity) {
    String[] projection = { MediaColumns.DATA };
    Cursor cursor = activity
            .managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

}

0 个答案:

没有答案