java - Android写入文件

标签 java android file-upload file-io

我正在尝试写入一个文件并上传它,但是,该文件似乎没有正确写入(稍后我需要上传它,它崩溃并说没有文件)。我遵循 Google 的指南 documentation .这是我的代码:

    String fileLocation = "Hello";
    String TESTSTRING = new String("Hello Android");

    FileOutputStream fOut = openFileOutput(fileLocation, MODE_WORLD_READABLE);

    fOut.write(TESTSTRING.getBytes());
    fOut.close();

这就是我尝试上传的方式:

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

    String pathToOurFile = fileLocation;

    String Tag = "UPLOADER";
    HttpURLConnection conn = null;



    String urlServer = "http://..."; //my server
      String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            // ------------------ CLIENT REQUEST

            Log.e(Tag, "Inside second Method");

            FileInputStream fileInputStream = new FileInputStream(new File(fileLocation));
            // open a URL connection to the Servlet
            URL url = new URL(urlServer);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");

            conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

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

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos
                    .writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                            + fileLocation + "" + lineEnd);
            dos.writeBytes(lineEnd);

            Log.e(Tag, "Headers are written");

            // create a buffer of maximum size

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

            // read file and write it into form...

            int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

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

            // send multipart form data necesssary after file data...

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

            // close streams
            Log.e(Tag, "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Log.e(Tag, "error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe) {
            Log.e(Tag, "error: " + ioe.getMessage(), ioe);
        }

        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                Log.e("Dialoge Box", "Message: " + line);
            }
            rd.close();

        } catch (IOException ioex) {
            Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
        }
    }

这是服务器上的 PHP 代码:

$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
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!";
}

最佳答案

而不是使用

FileInputStream fileInputStream = new FileInputStream(new File(fileLocation));

使用

FileInputStream fileInputStream = openFileInput(fileLocation);

关于java - Android写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8314276/

相关文章:

java - 为什么 fill3DRect 在我自己的计算机之外的其他计算机上无法正常工作?

java - Setter 注释在 Java 类中不起作用

android - 未调用最小宽度尺寸 xml

android - 如何将drawableLeft对齐到顶部而不是在android TextView中居中?

jquery 文件上传插件 : How to change the upload path?

ios - 上传的视频没有显示在 vine 应用程序上

java - 如何消除这个jsp错误

java进程构建器使用其他目录启动cmd

java - 奇怪的 SocketExceptions : connection reset and Connection timed out

iphone - 使用SFTP协议(protocol)从iPhone上传文件