2016-03-24 6 views
0

アンドロイドギャラリーからサーバーフォルダに画像をアップロードできません。これは例外ではなく、画像はフォルダにアップロードされません。すべてのサンプルのサンプルをグーグルで試して、多くのソリューションを試してみましたが、何も私のために働く。複数の部分からサーバーへの画像アップロードがアンドロイドで機能していません

package net.simplifiedcoding.volleyupload; 

import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

public class UploadImageDemo extends Activity { 

TextView tv; 
Button b; 
int serverResponseCode = 0; 
ProgressDialog dialog = null; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    b = (Button)findViewById(R.id.but); 
    tv = (TextView)findViewById(R.id.tv); 
    tv.setText("Uploading file path :- '/storage/sdcard0/DCIM/Camera/IMG_20160112_104150.jpg'"); 

    b.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      dialog = ProgressDialog.show(UploadImageDemo.this, "", "Uploading file...", true); 
      new Thread(new Runnable() { 
       public void run() { 
        runOnUiThread(new Runnable() { 
         public void run() { 
          tv.setText("uploading started....."); 
         } 
        }); 
        int response= uploadFile("/storage/sdcard0/DCIM/Camera/IMG_20160112_104150.jpg"); 

       } 
      }).start(); 
     } 
    }); 
} 

public int uploadFile(String sourceFileUri) { 
    String upLoadServerUri = "http://appsinbox.com/appstimesheetnew/testup.php"; 
    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()) { 
     Log.e("uploadFile", "Source File Does not exist"); 
     return 0; 
    } 
    try { // open a URL connection to the Servlet 
     FileInputStream fileInputStream = new FileInputStream(sourceFile); 
     URL url = new URL(upLoadServerUri); 
     conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL 
     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); 
     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); 

     bytesAvailable = fileInputStream.available(); // create a buffer of maximum size 

     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(); 
     final String serverResponseMessage = conn.getResponseMessage(); 

     Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); 
     if(serverResponseCode == 200){ 
      runOnUiThread(new Runnable() { 
       public void run() { 
        tv.setText("File Upload Completed."); 

       } 
      }); 
     } 

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

    } catch (MalformedURLException ex) { 
     dialog.dismiss(); 
     ex.printStackTrace(); 

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

    } 
    dialog.dismiss(); 
    return serverResponseCode; 
} 
} 

とPHPコードこれは私が(:)多かれ少なかれ)、それをやった方法です

$target_path1 = "/var/www/vhosts/logineduhub.com/appsinbox/appstimesheetnew/uploads/"; 
/* Add the original filename to our target path. Result is "uploads/filename.extension" */ 
$target_path1 = $target_path1 . basename($_FILES['uploaded_file']['name']); 
if(chmod($target_path1, 0777)) { 
// more code 
chmod($target_path1, 0755); 

if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) 
    { 
     echo "hi"; 
    echo "The first file " . basename($_FILES['uploaded_file']['name']) . " has been uploaded."; 
} 
else { 
    echo "bye"; 
    echo "There was an error uploading the file, please try again!"; 
    echo "filename: " . basename($_FILES['uploaded_file']['name']); 
    echo "target_path: " . $target_path1; 
} 


} 
else 
{ 
echo "Couldn't do it."; 
} 
+0

logcatの中に何か?メインスレッドでネットワーキングを行っていますが、これは正しい方法ではありません。 – Egor

+0

のアンドロイド部分は、画像をアップロードするためにピカソライブラリを使用することができます –

+0

logcat @ Egorに何もない –

答えて

0

を下回っている

アンドロイド:

public String uploadFile(String u, String imageFilePath, String filename) { 

    String attachmentName = "image"; 
    String attachmentFileName = filename + ".jpg"; 
    String crlf = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 

    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 

    StringBuffer response = new StringBuffer(); 

    try { 
     FileInputStream fileInputStream = new FileInputStream(imageFilePath); 

     try { 

      HttpURLConnection httpUrlConnection = null; 
      URL url = new URL(u); 
      httpUrlConnection = (HttpURLConnection) url.openConnection(); 
      httpUrlConnection.setUseCaches(false); 
      httpUrlConnection.setDoOutput(true);     

      httpUrlConnection.setRequestMethod("POST"); 
      httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); 
      httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); 
      httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 

      DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream()); 

      request.writeBytes(twoHyphens + boundary + crlf); 
      request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf); 
      request.writeBytes(crlf); 

      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

      while (bytesRead > 0) { 
       request.write(buffer, 0, bufferSize); 
       bytesAvailable = fileInputStream.available(); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
      } 

      request.writeBytes(crlf); 
      request.writeBytes(twoHyphens + boundary + twoHyphens + crlf); 

      request.flush(); 
      request.close(); 

      int responseCode = httpUrlConnection.getResponseCode(); 

      String inputLine = ""; 

      if (responseCode == 200) { 
       BufferedReader in = new BufferedReader(
         new InputStreamReader(httpUrlConnection.getInputStream())); 
       while ((inputLine = in.readLine()) != null) { 
        response.append(inputLine); 
       } 
       in.close(); 
      } 

     } catch (MalformedInputException e) { 
      Log.v("Err", e.getMessage()); 
     } catch (ConnectException e) { 
      Log.v("Err", e.getMessage()); 
     } catch (UnknownHostException e) { 
      Log.v("Err", e.getMessage()); 
     } catch (Exception e) { 
      Log.v("Err", e.getMessage()); 
     } 

    } catch (FileNotFoundException e) { 
     Log.v("Err", e.getMessage()); 
    } 

    return response.toString(); 

} 

とPHP

<?php 

    define('DS',DIRECTORY_SEPARATOR);  

    $response = 0; 

    if($_FILES){   
     if(!$_FILES['image']['error']){ 
      if(is_uploaded_file($_FILES['image']['tmp_name'])){     

       $dirpath = 'path to save file'; 

       if(!is_dir($dirpath)){ 
        mkdir($dirpath,0777); 
       } 

       $destination = $dirpath.DS.$_FILES['image']['name']; 
       if(move_uploaded_file($_FILES['image']['tmp_name'], $destination)){ 
        $response = 1; 
       } 
      } 
     } 
    } 

    echo $response; 

?> 
+0

PHPコードでDIRECTORY_SEPARATORとは何ですか? –

+0

[doc](http://php.net/manual/en/dir.constants.php)ここがすべてです – Bart

+0

このコードもあまりにもうまくいかない:( –

関連する問題