Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.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
使用多部分数据请求将图像从android上载到服务器_Android_Codeigniter_Upload - Fatal编程技术网

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

使用多部分数据请求将图像从android上载到服务器,android,codeigniter,upload,Android,Codeigniter,Upload,我想从我的android应用程序上传一个图像到服务器上。我使用了这个代码() 问题是图像已成功上载到我的数据库,但未上载到文件夹 这是我的服务器代码(codeigniter): 这是android代码: public class Image extends Activity { private static final int REQUEST_IMAGE = 100; ImageView preview; File destination; String imagePath; Button

我想从我的android应用程序上传一个图像到服务器上。我使用了这个代码()

问题是图像已成功上载到我的数据库,但未上载到文件夹

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

这是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,但它不起作用。

现在它起作用了,因为我的服务器更改了文件夹文件,所以我再次将其更改为777。现在我在文件夹和数据库中有一个不同的图像名称,我不知道为什么?你要重命名文件吗?似乎不是。您的
$img
$url
变量由不同的
uniqueid(rand())
组成。使用相同的名称并重命名该文件。我对这个很感兴趣,请告诉我它是否有效或者你是如何解决的。
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
}