为什么无法将图像上传到服务器(公用文件夹)

时间:2015-01-29 12:57:40

标签: php android hosting

我有一个可以将图像上传到服务器的Android应用程序。在localhost中,这没有问题,但在使用托管服务器后,图像无法移动到公用文件夹。关于数据库没问题。我使用000webhost进行托管。有人能帮助我吗?

这是我的网站链接http://hymustre.comyr.com/?page_id=34

这里是我的java文件

public class AddPostWisata extends Activity {
TextView messageText,textFilePath;
EditText etinfo;
EditText alinfo;
ImageView imageTampil;
ImageView uploadButton;
ImageView cariFile;
int serverResponseCode = 0;


//String pathFile = "http://galeri.programmermuslim.in/dashbord/img/galeri/";
// [baru] String pathFile = "http://10.0.2.2/img/galeri";
//String pathFile = "http://192.168.43.2/wordpress/wp-content/uploads/al_gallery_files/ai_photo_files/";

String pathFile = "http://hymustre.comyr.com/wp-content/uploads/al_gallery_files/ai_photo_files/";


ProgressDialog dialog = null;   
String upLoadServerUri = null;
String userName, id_register;
public Uri UrlGambar;
private static final int FILE = 1;
//public static final String TAG_USERNAME="username";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
//private static String url_tambah_anggota = "http://galeri.programmermuslim.in/json/insert_image.php";

// [baru] private static String url_tambah_anggota = "http://10.0.2.2/uploads/insert_image.php";



//private static String url_tambah_anggota = "http://192.168.43.2/to_db/insert_image.php";


private static String url_tambah_anggota = "http://hymustre.comyr.com/to_db/insert_image.php";

//  inisialisasi nama node dari json yang dihasilkan oleh php (utk class ini hanya node "sukses")
private static final String TAG_SUKSES = "sukses";


//get curent date
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String date = df.format(Calendar.getInstance().getTime());



@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.post_infowisata);

  //  Intent i = getIntent();
   // userName = i.getStringExtra(TAG_USERNAME);
    //Toast.makeText(getApplicationContext(), userName, Toast.LENGTH_LONG).show();

    uploadButton = (ImageView)findViewById(R.id.postTambahPost);
    messageText  = (TextView)findViewById(R.id.pathFile);
    textFilePath = (TextView)findViewById(R.id.postNamaFile);
    cariFile = (ImageView) findViewById(R.id.postPilihPhoto);
    imageTampil = (ImageView) findViewById(R.id.postTampilPhoto);
    etinfo = (EditText) findViewById(R.id.postTeksPost);
    alinfo = (EditText) findViewById(R.id.postAlbum);

    cariFile.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();

            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Pilih Aplikasi"), FILE);
        }


    });



    messageText.setText("Uploading file path :- '"+pathFile+"'");

    /************* Php script path ****************/
    upLoadServerUri = ParamConst.SERVER_PHP;

    uploadButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                new UploadGambar().execute();
            }
        });
}
/**
 * Background Async Task untuk menambah data anggota baru
 * */
class UploadGambar extends AsyncTask<String, String, String> {

    /**
     * sebelum memulai background thread tampilkan Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AddPostWisata.this);
        pDialog.setMessage("Upload image..please wait");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * menambah data
     * */
    protected String doInBackground(String... args) {
        String info_wisata;

        String info_album;
        //String home = null;





        //String tgl_informasi= getCurrentDate();
        info_wisata = etinfo.getText().toString();      
        String foto_wisata= getRealName(UrlGambar);


        info_album = alinfo.getText().toString();   

        /*
        if(info_album == home){

            info_album = ;
        }
        */  



        //Intent i = getIntent();
    //  userName = i.getStringExtra(TAG_USERNAME);
        //String username = userName ;
        //id_register = "3";                

        if(pathFile == null){
            Toast.makeText(AddPostWisata.this, "Tolong pilih gambar yang akan di upload", Toast.LENGTH_LONG).show(); 

         }else{

                      //  dialog = ProgressDialog.show(AddPostWisata.this, "", "Sedang mengupload gambar...", true);

                        new Thread(new Runnable() {
                                public void run() {
                                     runOnUiThread(new Runnable() {
                                            public void run() {
                                                messageText.setText("uploading started.....");
                                            }
                                        });                      


                                        uploadFile(pathFile);


                                }
                              }).start();  
         }   

        //if(info_album == home) && (){
        // membangun Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("judul", info_wisata));
        params.add(new BasicNameValuePair("pict", foto_wisata));
        params.add(new BasicNameValuePair("album", info_album));
        params.add(new BasicNameValuePair("tanggal", date));

        // mengambil JSON Object
        //dengan method POST
        JSONObject json = jsonParser.makeHttpRequest(url_tambah_anggota,"POST", params);

        // periksa log cat respon
        Log.d("Respon tambah anggota", json.toString());

        // check for success tag
        try {
            int sukses = json.getInt(TAG_SUKSES);

            if (sukses == 1) {
                // jika sukses menambah data baru

                Intent i = new Intent(getApplicationContext(), ActivityGaleriUtama.class);
                startActivity(i);

                //Toast.makeText(AddPostWisata.this, "File Upload success.", 
                  //   Toast.LENGTH_SHORT).show();
                // tutup activity ini
                finish();
            } else {
                // jika gagal dalam menambah data
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //}
        return null;
        //}
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // hilangkan dialog ketika selesai menambah data baru
        pDialog.dismiss();
    }

}
//mengambil tanggal sekarang    
/*private String getCurrentDate() {
    Date current = new Date();
    SimpleDateFormat frmt = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = frmt.format(current);
    return dateString;
    }*/



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    //check supaya ketika di pencet tombol back tidak error (mengantisipasi nilai null pada data)   
    if(data != null){
        UrlGambar = data.getData();
         Log.d("","URI = "+ UrlGambar);                                       
         if (UrlGambar != null && "content".equals(UrlGambar.getScheme())) {
             Cursor cursor = this.getContentResolver().query(UrlGambar, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
             cursor.moveToFirst();   
             pathFile = cursor.getString(0);

             cursor.close();
         }
         else {
             pathFile = UrlGambar.getPath();
         }
         Log.d("","Chosen path = "+ pathFile);
        //--------------------------------GET URI FOR IMAGES-----------------------------------------


        textFilePath.setText(pathFile);
        imageTampil.setImageURI(UrlGambar);
    }

}

public int uploadFile(String sourceFileUri) {


    int MAX_IMAGE_SIZE = 200 * 1024; // max final file size
    int compressQuality = 75; // quality decreasing by 5 every loop. (start from 99)
    int streamLength = MAX_IMAGE_SIZE;




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

      if (!sourceFile.isFile()) {

           //dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                               +pathFile);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           +pathFile);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);



               BufferedInputStream buf = new BufferedInputStream(new FileInputStream(sourceFile));

               //bitmap gambar inisialisasi
               Bitmap bmpPic = BitmapFactory.decodeFile( sourceFile.getPath());

               if ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) {
                BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
                bmpOptions.inSampleSize = 1;
                while ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) {
                    bmpOptions.inSampleSize++;
                    bmpPic = BitmapFactory.decodeFile(sourceFile.getPath(), bmpOptions);
                }
                //Log.d(TAG, "Resize: " + bmpOptions.inSampleSize);
            }
             //-----------------------------------------------------------------  




               // 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("uploaded_file", fileName); 

               Log.i(">>>>>>>>>A<<<<<<<<<", upLoadServerUri);
               Log.i(">>>>>>>>>B<<<<<<<<<", fileName);

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

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



              // BufferedImage image = ImageIO.read(file);




               while (bytesRead > 0 && streamLength >= MAX_IMAGE_SIZE)  {

                /* dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
                 */



                   //coba compress image
                 ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
                 compressQuality -= 5;
                // Log.d(TAG, "Quality: " + compressQuality);
                 bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
                 byte[] bmpPicByteArray = bmpStream.toByteArray();
                 streamLength = bmpPicByteArray.length;
                 //---------------------------------------

                 //percobaan
                 dos.write(bmpPicByteArray, 0, streamLength);
                 bytesAvailable = buf.available();
                 bufferSize = Math.min(bytesAvailable, streamLength);
                 bytesRead = buf.read(bmpPicByteArray, 0, streamLength);
                 //-------------------------------------------------------
                }

               //part output stream
               FileOutputStream bmpFile = new FileOutputStream(pathFile);
            bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile);
            //--------------------------------------------------------



               // 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() {

                            //String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                //          +upLoadServerUri;


                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +"http://hymustre.comyr.com/wp-content/uploads/al_gallery_files/ai_photo_files/"; 

                            /*
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                      +"http://192.168.43.2/wp-content/uploads/al_gallery_files/ai_photo_files/";
                            */

                            messageText.setText(msg);
                            Toast.makeText(AddPostWisata.this, "File Upload Complete.", 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

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


               //buf close
               buf.close();
               //---------------------------

               dos.flush();
               dos.close();

               //bmpFile.flush();
               //bmpFile.close();

          } catch (MalformedURLException ex) {

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

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(AddPostWisata.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

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

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

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(AddPostWisata.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 
     } 
public String getRealPath(Uri contentUri)
{
    String path = null;
    String[] images_data = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(contentUri, images_data, null, null, null);
    if(cursor.moveToFirst())
    {
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       path = cursor.getString(column_index);
    }
    cursor.close();
    return path;
}

public String getRealName(Uri contentUri)
{
Uri path= contentUri;
String filename= "";
String[] images_data = { MediaStore.Images.Media.DATA };

if (contentUri.getScheme().toString().compareTo("content")==0)
{ 
Cursor cursor = getContentResolver().query(contentUri, images_data, null, null, null);
if(cursor.moveToFirst())
{
   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   path = Uri.parse(cursor.getString(column_index));
   filename = path.getLastPathSegment().toString();

}
cursor.close();
}
return filename;
}

}

这是php脚本和上传路径的链接

public class ParamConst {

public final static String SERVER_PHP = "http://hymustre.comyr.com/to_db/UploadToServer.php";

public final static String PATH_TO_UPLOAD = "http://hymustre.comyr.com/wp-content/uploads/al_gallery_files/ai_photo_files/";

}

这是我的php代码

<?php

$file_path='/home/a6362811/public_html/wp-content/uploads/al_gallery_files/ai_photo_files/';

$file_path_twoo='/home/a6362811/public_html/wp-content/uploads/al_gallery_files/ai_photo_files/al_photo_thumb_files/';

$filename = basename( $_FILES['uploaded_file']['name']);

$file_path = $file_path . $filename;

$success = move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path);

if( $success ) {
chmod($file_path, 0777);
}


$pathToImages='/home/a6362811/public_html/wp-content/uploads/al_gallery_files/ai_photo_files/';

$pathToThumbs='/home/a6362811/public_html/wp-content/uploads/al_gallery_files/ai_photo_files/al_photo_thumb_files/';

$thumbWidth = 200;

$fname = $filename;

function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth ) 
{
// Turn off all error reporting
error_reporting(0);

set_time_limit(0);
  // open the directory
  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPG files:
  $i='1';
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
        /*$source_file_name = basename($source_image);
        $source_image_type = substr($source_file_name, -3, 3);*/

        $source_file_name = basename($fname);
        $source_image_type = substr($source_file_name, -3, 3);

        switch(strtolower($info['extension']))
        {
        case 'jpg':
            $img = imagecreatefromjpeg("{$pathToImages}{$fname}");
            break;

        case 'gif':
            $img = imagecreatefromgif("{$pathToImages}{$fname}");
            break;

        case 'png':
            $img = imagecreatefrompng("{$pathToImages}{$fname}");
            break;    
        }

      echo "$i : Creating thumbnail for small_$fname <br />";

      // load image and get image size
      $width = imagesx( $img );
      $height = imagesy( $img );

    // this will be our cropped image

    // copy the crop area from the source image to the blank image created above

    // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = $thumbWidth;

      // create a new tempopary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );


      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );



    $extension_pos = strrpos($fname, '.'); // find position of the last dot, so where the extension starts
    $thumb = substr($fname, 0, $extension_pos) . '-thumb' . substr($fname, $extension_pos);


    switch(strtolower($info['extension']))
    {

        case 'jpg':
            imagejpeg($tmp_img, "{$pathToThumbs}$thumb", 100);
            break;

        case 'gif':
            imagegif($tmp_img, "{$pathToThumbs}$thumb");
            break;

        case 'png':
            imagepng($tmp_img,"{$pathToThumbs}$thumb", 0);
            break;    
    }
    imagedestroy($img);
    imagedestroy($tmp_img);
    $i++;
      }
  // close the directory
  closedir( $dir );
}

createThumbs($pathToImages,$pathToThumbs,200);

?>

0 个答案:

没有答案