【问题标题】:Android AsyncTask Upload FilesAndroid AsyncTask 上传文件
【发布时间】:2013-07-11 18:18:32
【问题描述】:

我想上传一些存储在 android 设备上的文件,但它似乎卡在了 AsyncTask 的 doInBackground 方法中。我没有错误。对话框弹出并保持活动状态我消除了对话框并且没有效果。我项目的另一部分是解码我上传的 json 文件并将它们存储在数据库中,但那是为了以后。

    /********************UPLOAD GPSDATA*************************************/
class UploadGpsData extends AsyncTask<Void, Void, Void>{

    NetworkInfo net;

    MainActivity uActivity;

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;

    String folderPath;
    String arrayOfFiles[];
    File root;
    File allFiles;

    String urlServer = "http://urluploadscriptaddress.php";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

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

    URL url;

     ProgressDialog pDialog = new ProgressDialog(MainActivity.this);



    @Override
    protected void onPreExecute() {


        Log.d(" UploadGpsData","onPreRequest");

            pDialog.setMessage("Uploading GPS Data. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();


    }

    @Override
    protected Void doInBackground(Void... params) {

         Log.d(" UploadGpsData","doInBackground");

        root = Environment.getExternalStorageDirectory(); 

        //pathToOurFile = root.getAbsolutePath()+"/Beagle Data/07-09-2013_16-21-30.json";

        folderPath = root.getAbsolutePath()+"/Beagle Data/";

        allFiles = new File(folderPath);

        arrayOfFiles = allFiles.list(); 




        for(int i = 0; i < arrayOfFiles.length; i++){

            Log.d("File Names", arrayOfFiles[i].toString());
            //File filename = new File(arrayOfFiles[i].toString());
            try {
                url = new URL(urlServer);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                connection = (HttpURLConnection) url.openConnection();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

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

            // Enable POST method
            try {
                connection.setRequestMethod("POST");
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
            try{

            FileInputStream fileInputStream = new FileInputStream(new File(folderPath+arrayOfFiles[i].toString()) );
            try {
                outputStream = new DataOutputStream( connection.getOutputStream() );
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + folderPath+arrayOfFiles[i].toString() +"\"" + 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);

            }

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

            //int serverResponseCode = connection.getResponseCode();
            //String serverResponseMessage = connection.getResponseMessage();

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

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
            } catch(Exception e){
                e.printStackTrace();
            }

        }


    return null;
    }

    protected void onPostExecute() {

         Log.d(" UploadGpsData","onPost");

        pDialog.dismiss();

        txtUploadStatus = (TextView) findViewById(id.txtUploadStatus);

        txtUploadStatus.setText("Upload Achieved");
    }
}
/********************END OF UPLOADGPSDATA*************************************/

下面的 PHP 脚本:错误日志是空的,所以我假设它卡在 android 应用程序上

<?php
$target_path  = "./";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

$file = basename( $_FILES['uploadedfile']['name']);

move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
?>

【问题讨论】:

  • 您是否尝试过单步执行代码?
  • 是的,我有。我有 3 个文件,每一步我都放了一个 log.d。最后一个 log.d 在返回之前并保留在那里。 onPost 从不显示。

标签: php android file-upload android-asynctask


【解决方案1】:

您没有实现@Override onPostExecute。

用这个修改你的 onPostExecute 分配:

@Override
protected void onPostExecute(Void result) {

这将解决您的问题。 发生了什么事: 您没有覆盖 OnPostExecute AsyncTask 方法,而是创建了一个新方法。

【讨论】:

  • 谢谢。我已经进行了这些更正,并且 onPost 出现了。但我的文件没有上传。
【解决方案2】:

您缺少paramsonPostExecute() 可能是一个问题

    @Override
    protected void onPostExecute(Void result) {

即使您没有从doInBackground() 返回任何内容,您仍然需要将其作为AsyncTask 方法。如果这不能解决问题,那么还请发布您是如何调用它的,并说明您是否在任何地方设置了断点以查看它在做什么。

【讨论】:

  • 我放置了您发布的代码,并且 onPost 正在显示。我从上课开始就做了断点,一切都很好。我是这样称呼它的:new UploadGpsData().execute();文件仍未上传。现在我注意到日志中弹出一条绿色的消息:跳过 1034 帧应用程序可能在其主线程上做了很多工作。
  • 那么AsyncTask现在运行成功了吗?除非我错过了什么,否则我看不到任何会导致这种情况的东西。它可能来自代码中的其他地方,在任务运行之前还是之后?
  • 如果我取出包含文件名列表的for循环,它将上传一个文件。
  • 您可以尝试从for loop 中取出不需要每次都重置的内容。另外,你怎么称呼这个任务?
【解决方案3】:

您在非 UI 线程中“操纵”UI。

尝试注释所有与 UI 相关的代码,它应该可以工作。

你可以使用

Context.runOnUiThread(new Runnable() ....

为了做 UI 的东西。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 2011-05-23
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多