0

私は Android プログラミングの初心者で、画像をサーバーにアップロードしようとしていました。ここでいくつかのコードをstackoverflowで見つけました。調整しましたが、まだ機能しません。

問題は、私の画像がまだアップロードされないことです。

編集問題を解決しました。サーバー上のフォルダーに対する権限がありませんでした。今、私は新しい問題を抱えています。プログレスバーが機能しません。送信率 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!";
 }
 ?>  

誰かが私を助けてくれれば本当にありがたいです。

4

1 に答える 1

0

onCreate() でビューにアクセスできるようにすることは想定されていません。一部のコードを onStart() に移動してみてください。

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

    registerButtonCallbacks();
}

コードを実行していないので、他にも欠陥があるかどうかはわかりません。

于 2012-09-02T21:11:41.880 に答える