使用多部分数据请求将图像从android上传到服务器

时间:2015-04-07 09:35:56

标签: android codeigniter upload

我想将我的Android应用程序中的图像上传到服务器。我使用了这段代码(code)。

问题是图像已成功上传到我的数据库,但没有上传到文件夹。

这是我的服务器代码(codeigniter):

private function do_upload(){
    $type = explode('.', $_FILES["image_user"]["name"]);
    print_r($type);
    $type = strtolower($type[count($type)-1]);

    $img=uniqid(rand()).'.'.$type;
    $url = "./images/".uniqid(rand()).'.'.$type;
    if(in_array($type, array("jpg", "jpeg", "gif", "png")))
        if(is_uploaded_file($_FILES["image_user"]["tmp_name"]))
            if(move_uploaded_file($_FILES["image_user"]["tmp_name"],$url))
                return $img;
    return "";
}

public function update_image_post(){
    $username = $this->get('username');
    $url = $this->do_upload();
    $this->Users_model->update_image($username, $url);
}

这是android代码:

public class Image extends Activity {

private static final int REQUEST_IMAGE = 100;

ImageView preview;
File destination;
String imagePath;
Button takePhoto;
Button btnCreate;

int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.image_main);
    preview = (ImageView) findViewById(R.id.uploadImage);
    takePhoto = (Button) findViewById(R.id.selectImageButton);
    btnCreate = (Button) findViewById(R.id.uploadButton) ;

    preview.setVisibility(View.GONE);

    upLoadServerUri = "http://myserver/api/users/update_image/username/mimi/";

    String name = dateToString(new Date(),"yyyy-MM-dd-hh-mm-ss");
    destination = new File(Environment.getExternalStorageDirectory(), name + ".jpg");

    takePhoto.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
            startActivityForResult(intent, REQUEST_IMAGE);
        }
    });

    btnCreate.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(Image.this, "", "Uploading file...", true);

            new Thread(new Runnable() {
                public void run() {
                    uploadFile(imagePath);
                }
            }).start();
        }

    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
        try {
            preview.setVisibility(View.VISIBLE);
            takePhoto.setVisibility(View.GONE);
            FileInputStream in = new FileInputStream(destination);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 10;
            imagePath = destination.getAbsolutePath();
            Log.d("INFO", "PATH === " + imagePath);
            //tvPath.setText(imagePath);
            Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
            preview.setImageBitmap(bmp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

public String dateToString(Date date, String format) {
    SimpleDateFormat df = new SimpleDateFormat(format);
    return df.format(date);
}


public int uploadFile(String sourceFileUri) {

    String fileName = sourceFileUri;

    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;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {
        dialog.dismiss();
        Log.e("uploadFile", "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("image_user", fileName);

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"image_user\";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){

                runOnUiThread(new Runnable() {
                    public void run() {

                     Toast.makeText(Image.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                    }
                });
           }

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

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {

                }
            });

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

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {

                   Toast.makeText(Image.this, "Got Exception : see logcat ",Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload file to server Exception", "Exception : "
                    + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

我将文件夹权限更改为777,但它无法正常工作。

0 个答案:

没有答案