Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 文件上载无法正常运行_Java_Android_File Upload - Fatal编程技术网

Java 文件上载无法正常运行

Java 文件上载无法正常运行,java,android,file-upload,Java,Android,File Upload,我有以下文件上传功能: public void uploadFile(Context context, File file) { String urlServer = "https://u-database.000webhostapp.com/recieve_file.php"; if(file.isFile() && file.exists()) { String fileName = file.getAbsolu

我有以下文件上传功能:

    public void uploadFile(Context context, File file) {
        String urlServer = "https://u-database.000webhostapp.com/recieve_file.php";
        if(file.isFile() && file.exists()) {
            String fileName = file.getAbsolutePath();
            try {
                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;
                Toast toastw = Toast.makeText(context, "Inside TRY", Toast.LENGTH_SHORT);
                toastw.show();

                FileInputStream fileInputStream = new FileInputStream(file);
                URL url = new URL(urlServer);

                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection();
                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("textLog", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"textLog\";filename=\""+fileName+"\""+lineEnd);
                dos.writeBytes(lineEnd);

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

                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)
                int serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                Toast toast = Toast.makeText(context, "Uploading", Toast.LENGTH_SHORT);
                toast.show();

                if(serverResponseCode == 200){
                    file.delete();
                    Toast toasto = Toast.makeText(context, "success", Toast.LENGTH_SHORT);
                    toasto.show();
                }

                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                Toast toast = Toast.makeText(context, "Malformed URL", Toast.LENGTH_SHORT);
                toast.show();
            } catch (Exception e) {
                Toast toast = Toast.makeText(context, "Exception", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }
每次执行时,都会出现一个toast,说明内部尝试,然后出现另一个toast,说明“异常”。

我一直在调试,非常感谢您的帮助:)

更新


当我做了
e.toString
并把它打印出来作为祝酒词时,我得到了:
android.os.NetworkOnMainThreadException
那么答案很简单。您应该在后台线程上运行网络调用。您需要扩展
AsyncTask
,并将代码移到其中。比如:

private class InitTask extends AsyncTask<Void, Void, Void>{
      protected Void doInBackground(Void... p){
         // Call upload file code here
      }
}
私有类InitTask扩展了异步任务{
受保护的空位背景(空位…p){
//在这里调用上传文件代码
}
}

如果您检查了
ex
提供的功能(例如
printStackTrace
或类似功能),它会告诉您更多信息,@Itamagreen感谢您的关注,它通常是BroadcastReceiver的一部分,因此我无法在AVD中调试它,因为它没有任何活动。所以基本上是没有希望的。你知道获取stacktraces的其他方法吗?好吧,要记录异常,你可以参考这里:@Itamagreen where?我没有看到链接,你不能编辑代码并打印出异常的toString()吗?它可以是一个内部类吗?当然可以。您可以在本教程中查看更多解释和示例:。缺少return语句@DoronYakovlev golanisold通过添加return null来解决它,现在就测试它。但我真的不能在那里显示祝酒词。这只是一个伪代码框架(我没有编译它)。。。你必须填写细节。