java - 文件上传不工作android

标签 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.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,说明 Inside TRY,然后出现另一个说明“Exception”。

我一直在进行大量调试,非常感谢任何形式的帮助:)

更新

当我执行 e.toString 并将其打印到 toast 时,我得到:android.os.NetworkOnMainThreadException

最佳答案

答案很简单。您应该在后台线程上运行网络调用。您需要扩展 AsyncTask 并将您的代码移入其中。像这样的东西:

private class InitTask extends AsyncTask<Void, Void, Void>{
      protected Void doInBackground(Void... p){
         // Call upload file code here
      }
}

关于java - 文件上传不工作android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43848134/

相关文章:

java - 如何将最初的第一个用户添加到网络应用程序用户列表中(该用户随后会添加其他用户)?

java - 是否可以避免将对象声明为final?

java - 使用 Android 服务发送电子邮件

javascript - 从表单中删除输入后提交失败(在 Firefox 中)

javascript - Angular上传图像并显示给用户

php - 无法修复错误 "failed to open stream: HTTP wrapper does not support writeable connections"

java - 在 Elasticsearch 中使用 ngram 进行搜索

java - 切换动态工具提示 - java swing

java - 在 Fragment 中使用 CustomView 发生 ClassCastException

android - 使用 volley 上传 pdf 但在服务器文件夹上获取空文件