2016-03-24 13 views
0

Android galeriden sunucu klasörüne görüntü yükleniyor çalışmıyor. Herhangi bir istisna değildir ve görüntü klasöre yüklenmez. Tüm örnek örneklerini inceledim ve birçok çözüm denedim ama hiçbir şey benim için işe yaramıyor.Resim, sunucu klasörüne çok bölümlü olarak yükleme android çalışıyor Not

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; 
} 
} 

Ve php kodu Bu ben yaptım nasıl

$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 içinde herhangi bir şey var mı? Ana iş parçacığı üzerinde ağ yapıyorsunuz, bu doğru bir yol değil. – Egor

+0

android bölümü için, resim yüklemek için picasso kütüphanesini kullanabilirsiniz –

+0

Logcat @Egor –

cevap

0

altındadır (daha fazla veya daha az :))

Android:

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(); 

} 

ve 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 kodunda DIRECTORY_SEPARATOR nedir? –

+0

[doc] (http://php.net/manual/en/dir.constants.php) işte her şey – Bart

+0

Bu kod benim için de çalışmıyor :( –