2012-09-02 79 views
0

我是Android編程的初學者,我試着將圖片上傳到服務器。 我在這裏發現了一些代碼在stackoverflow,我調整它,它仍然無法正常工作。android upload progressbarr not working

問題是我的圖片仍然不會上傳。

編輯我解決了問題,我沒有在服務器上的文件夾的權利。 現在我有一個新問題。 progresbarr不起作用。它一直說0%傳輸

沒有人在我的代碼中看到錯誤?

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.Dialog; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.Window; 
import android.widget.Button; 
import android.widget.ImageView; 

import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class PreviewActivity extends Activity { 

/** The captured image file. Get it's path from the starting intent */ 
private File mImage; 

public static final String EXTRA_IMAGE_PATH = "extraImagePath" 

/** Log tag */ 
private static final String TAG = "DFH"; 

/** Progress dialog id */ 
private static final int UPLOAD_PROGRESS_DIALOG = 0; 
private static final int UPLOAD_ERROR_DIALOG = 1; 
private static final int UPLOAD_SUCCESS_DIALOG = 2; 


/** Handler to confirm button */ 
private Button mConfirm; 

/** Handler to cancel button */ 
private Button mCancel; 

/** Uploading progress dialog */ 
private ProgressDialog mDialog; 


/** 
* Called when the activity is created 
* 
* We load the captured image, and register button callbacks 
*/ 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 
    setContentView(R.layout.preview); 

    setResult(RESULT_CANCELED); 

    // Import image 
    Bundle extras = getIntent().getExtras(); 
    String imagePath = extras.getString(FotoActivity.EXTRA_IMAGE_PATH); 
    Log.d("DFHprev", imagePath); 
    mImage = new File(imagePath); 
    if (mImage.exists()) { 
     setResult(RESULT_OK); 
     loadImage(mImage); 
    } 

    registerButtonCallbacks(); 

} 

@Override 
protected void onPause() { 
    super.onPause(); 

} 

/** 
* Register callbacks for ui buttons 
*/ 
protected void registerButtonCallbacks() { 
    // Cancel button callback 
    mCancel = (Button) findViewById(R.id.preview_send_cancel); 
    mCancel.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      PreviewActivity.this.finish(); 
     } 
    }); 

    // Confirm button callback 
    mConfirm = (Button) findViewById(R.id.preview_send_confirm); 
    mConfirm.setEnabled(true); 
    mConfirm.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      new UploadImageTask().execute(mImage); 
     } 
    }); 
} 



/** 
* Initialize the dialogs 
*/ 
@Override 
protected Dialog onCreateDialog(int id) { 
    switch(id) { 
    case UPLOAD_PROGRESS_DIALOG: 
     mDialog = new ProgressDialog(this); 
     mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     mDialog.setCancelable(false); 
     mDialog.setTitle(getString(R.string.progress_dialog_title_connecting)); 
     return mDialog; 


    case UPLOAD_ERROR_DIALOG: 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setTitle(R.string.upload_error_title) 
       .setIcon(android.R.drawable.ic_dialog_alert) 
       .setMessage(R.string.upload_error_message) 
       .setCancelable(false) 
       .setPositiveButton(getString(R.string.retry), new   DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         PreviewActivity.this.finish(); 
        } 
       }); 
     return builder.create(); 

    case UPLOAD_SUCCESS_DIALOG: 
     AlertDialog.Builder success = new AlertDialog.Builder(this); 
     success.setTitle(R.string.upload_success_title) 
       .setIcon(android.R.drawable.ic_dialog_info) 
       .setMessage(R.string.upload_success_message) 
       .setCancelable(false) 
       .setPositiveButton(getString(R.string.success), new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         PreviewActivity.this.finish(); 
        } 
       }); 
     return success.create(); 

    default: 
     return null; 
    } 
} 

/** 
* Prepare the progress dialog 
*/ 
@Override 
protected void onPrepareDialog(int id, Dialog dialog) { 
    switch(id) { 
    case UPLOAD_PROGRESS_DIALOG: 
     mDialog.setProgress(0); 
     mDialog.setTitle(getString(R.string.progress_dialog_title_connecting)); 
    } 
} 

/** 
* Load the image file into the imageView 
* 
* @param image 
*/ 
protected void loadImage(File image) { 
    Bitmap bm = BitmapFactory.decodeFile(image.getPath()); 
    ImageView view = (ImageView) findViewById(R.id.preview_image); 
    view.setImageBitmap(bm); 
} 

/** 
* Asynchronous task to upload file to server 
*/ 
class UploadImageTask extends AsyncTask<File, Integer, Boolean> { 

    /** Upload file to this url */ 
    private static final String UPLOAD_URL = "http://www.xxxx.x/xxxx/fotos"; 

    /** Send the file with this form name */ 
    private static final String FIELD_FILE = "file"; 


    /** 
    * Prepare activity before upload 
    */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     setProgressBarIndeterminateVisibility(true); 
     mConfirm.setEnabled(false); 
     mCancel.setEnabled(false); 
     showDialog(UPLOAD_PROGRESS_DIALOG); 
    } 

    /** 
    * Clean app state after upload is completed 
    */ 
    @Override 
    protected void onPostExecute(Boolean result) { 
     super.onPostExecute(result); 
     setProgressBarIndeterminateVisibility(false); 
     mConfirm.setEnabled(true); 
     mDialog.dismiss(); 

     if (result) { 
      showDialog(UPLOAD_SUCCESS_DIALOG); 
     } else { 
      showDialog(UPLOAD_ERROR_DIALOG); 
     } 
    } 

    @Override 
    protected Boolean doInBackground(File... image) { 
     return doFileUpload(image[0], "UPLOAD_URL"); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... values) { 
     super.onProgressUpdate(values); 

     if (values[0] == 0) { 
      mDialog.setTitle(getString(R.string.progress_dialog_title_uploading)); 
     } 

     mDialog.setProgress(values[0]); 
    } 


    private boolean doFileUpload(File file, String uploadUrl) { 
     HttpURLConnection connection = null; 
     DataOutputStream outputStream = null; 
     DataInputStream inputStream = null; 

     String pathToOurFile = file.getPath(); 
     String urlServer = "http://www.xxxx.x/xxxx/upload.php"; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 

     // log pathtoourfile 
     Log.d("DFHinUpl", pathToOurFile); 

     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1*1024*1024; 
     int sentBytes = 0; 
     long fileSize = file.length(); 

     // log filesize 
     String files= String.valueOf(fileSize); 
     String buffers= String.valueOf(maxBufferSize); 
     Log.d("fotosize",files); 
     Log.d("buffers",buffers); 

     try 
     { 
     FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); 

     URL url = new URL(urlServer); 
     connection = (HttpURLConnection) url.openConnection(); 

     // Allow Inputs & Outputs 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 

     // Enable POST method 
     connection.setRequestMethod("POST"); 

     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); 

     outputStream = new DataOutputStream(connection.getOutputStream()); 
     outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
     outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd); 
     outputStream.writeBytes(lineEnd); 

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

     // Read file 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

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

     sentBytes += bufferSize; 
     publishProgress((int)(sentBytes * 100/fileSize)); 

     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     } 

     outputStream.writeBytes(lineEnd); 
     outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

     // Responses from the server (code and message) 
     int serverResponseCode = connection.getResponseCode(); 
     String serverResponseMessage = connection.getResponseMessage(); 



     fileInputStream.close(); 
     outputStream.flush(); 
     outputStream.close(); 
     try { 
      int responseCode = connection.getResponseCode(); 
      return responseCode == 200; 
     } catch (IOException ioex) { 
      Log.e("DFHUPLOAD", "Upload file failed: " + ioex.getMessage(), ioex); 
      return false; 
     } catch (Exception e) { 
      Log.e("DFHUPLOAD", "Upload file failed: " + e.getMessage(), e); 
      return false; 
     } 
     } 
     catch (Exception ex) 
     { 
      String msg= ex.getMessage(); 
     Log.d("DFHUPLOAD", msg); 
     } 
     return true; 
} 

} 
} 

處理這個上傳的PHP代碼如下:

<?php 
$date=getdate(); 

     $urldate=$date['year'].$date['month'].$date['month'].$date['hours'].$date['minutes'].$date[  'seconds']; 
$target_path = "./"; 
$target_path = $target_path . basename($_FILES['uploadedfile']['name']) . $urldate; 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedfile']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 
?> 

會很感激,如果有人可以幫助我。

+0

嗯,這裏有很多要測試。我認爲這個問題需要分解成更小的問題。有一件事,你正在將圖像加載到視圖中,並將其顯示在您的活動中。那樣有用嗎? 現在,在PHP ..缺少東西,通常$ _FILES var將來自POST GET;在你的情況下,一個端口的監聽器。也許這就是問題所在? – quinestor

+0

現在文件上傳正常。該文件在imageview中正確顯示。並且PHP代碼也可以工作。它只是有權限的東西。我已將文件夾權限設置爲777,並且工作正常。現在剩下的唯一問題是進度條。 – pieter

回答

0

視圖不應在onCreate()中可訪問。嘗試將一些代碼移動到onStart()。

@Override 
public void onStart() 
{ 
    super.onStart(); 
    mImage = new File(imagePath); 
    if (mImage.exists()) { 
     setResult(RESULT_OK); 
     loadImage(mImage); 
    } 

    registerButtonCallbacks(); 
} 

我還沒有運行代碼,所以我不知道是否還有其他缺陷。

+0

按鈕確實有用,但感謝您的回覆。現在我只需要使進度條跟隨文件上傳 – pieter

+0

你是對的。感謝你,我發現首先調用setContentView()就足夠了。 – loland

+0

不客氣:) – pieter