简体   繁体   中英

Upload a picture from an Android java application to Codeigniter

me and my friend have a problem when it comes to uploading a picture from an android application to the Codeigniter framework in php. The problem arises (we think) because it's not an image file and therefore can't be used for image operations.

One big notice is that the image upload works when tested with a html-page. And all the other data (like email) are provided and works in the android application. The only thing that do not work is the file upload. But it does work with another php file, but the question I have is how do I take the last php script that work and transform it into codeigniter? I want to use the framework for this, but so far we haven't been able to.

Here is the javacode for the upload ->

HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://url.com/controller-name");

try
{
  CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(new ProgressListener()
  {
    @Override
    public void transferred(long num)
    {
      publishProgress((int) ((num / (float) totalSize) * 100));
    }
  });

  // We use FileBody to transfer an image
  multipartContent.addPart("userfile", new FileBody(new File(filename)));
  totalSize = multipartContent.getContentLength();
  multipartContent.addPart("email", new StringBody("email@email.com"));
  multipartContent.addPart("submit", new StringBody("upload"));

  // Send it
  httpPost.setEntity(multipartContent);
  HttpResponse response = httpClient.execute(httpPost, httpContext);
  String serverResponse = EntityUtils.toString(response.getEntity());

  Log.i("SERVER", "Response: " + response.toString());
  return serverResponse;
}

catch (Exception e)
{
  System.out.println(e);
}

The codeigniter method for uploading:

function do_upload() {
    $image_name = time() . $this->get_random_string();
    $config = array(
        'file_name' => $image_name,
        'allowed_types' => 'jpg|jpeg|gif|png',
        'upload_path' => $this->gallery_path

    );
    $this->load->library('upload', $config);
    $this->upload->do_upload();
    $image_data = $this->upload->data();
    $config = array(
        'source_image' => $image_data['full_path'],
        'new_image' => $this->gallery_path . '/thumbs',
        'maintain_ratio' => false,
        'width' => 300,
        'height' => 300
    );

    $this->load->library('image_lib', $config);
    $this->image_lib->resize();
    echo $this->image_lib->display_errors();

    $image_name = $image_name . $image_data['file_ext'];
    //Insert into the database
    $data = array(
        'image_name' => $image_name,
        'upload_email' => $this->input->post('email'),
        'ip' => $this->input->ip_address()
    );

    // Insert the new data of the image!
    $insert = $this->db->insert('table', $data);
    $short_url = $this->alphaID($this->db->insert_id());

    return $short_url;

}

The older php script that works, notice is that the commented code does not work. Since it would probably give the same effect as CI does.

<?php
/*if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "application/octet-stream")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{*/
    if ($_FILES["file"]["error"] > 0)
    {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
    else
    {   
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("images/" . $_FILES["file"]["name"]))
        {
            echo $_FILES["file"]["name"] . " already exists. ";
        }
        else
        {
            move_uploaded_file($_FILES["file"]["tmp_name"],
                "images/" . $_FILES["file"]["name"]);
            echo "Stored in: " . "images/" . $_FILES["file"]["name"];
        }
    }
/*}
else
{
    echo "Invalid file";
}*/
?> 

Please help us modify either the CI-function or the java code so we can upload our beloved images. Thanks for your advice and better wisdom!

The answer was in the java-code. What I needed to add was some more parameters to the filebody.

  multipartContent.addPart("userfile", new FileBody(new File(filename), filename, "image/jpeg", "utf-8"));

This works flawlessly. Information about the filebody constructor you can find here: http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/content/FileBody.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM