android读取文件并上传

时间:2013-04-12 20:45:20

标签: android upload

我有一个代码:

 File myFile = new File("/sdcard/Pictures/MyCameraApp/1.jpg");
            FileInputStream fin = null;

                // create FileInputStream object
                try {
                    fin = new FileInputStream(myFile);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                byte fileContent[] = new byte[(int)myFile.length()];

                // Reads up to certain bytes of data from this input stream into an array of bytes.
                try {
                    fin.read(fileContent);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //create string from byte array
                String s = new String(fileContent);


        return new NanoHTTPD.Response(HTTP_OK, "image/jpeg", s);

但是当我使用浏览器时,我看到了一个损坏的JPEG文件。我究竟做错了什么?我想要一个用户在输入一些地址时看到1.jpg文件

修改:将代码更改为:

  File myFile = new File("/sdcard/Pictures/MyCameraApp/1.jpg");
            FileInputStream fin = null;

                // create FileInputStream object
                try {
                    fin = new FileInputStream(myFile);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int bytesRead;
                try {
                    while ((bytesRead = fin.read(b)) != -1) {
                       bos.write(b, 0, bytesRead);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                byte[] fileContent = bos.toByteArray();

                //create string from byte array
                String s = new String(fileContent);


        return new NanoHTTPD.Response(HTTP_OK, "image/jpg", s);

仍然不起作用.....当我进入页面时,我得到了损坏的jpg文件,(如果我写image / jpeg而不是image / jpg或text / html,则无法正常工作,将文本另存为jpg文件。完整地为文本工作:\

2 个答案:

答案 0 :(得分:2)

如何从Android中的文件读取字节

代码只是读取文件的开头。这就是到达服务器的 bytes 显示为损坏的图像文件的原因。

尝试以下代码修改:

fin = new FileInputStream(myFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = fin.read(b)) != -1) {
   bos.write(b, 0, bytesRead);
}
byte[] fileContent = bos.toByteArray();

当然,您必须包装所有适当的Exception处理程序。

答案 1 :(得分:-1)

这个解决方案不是我的,但可能很有用,模仿上传表格你可以找到来源here

class Utils {
    public static void upload(String filePath, String urlServer) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";

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

        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);
            }

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

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

            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        }
        catch (Exception ex) {
            //Exception handling
        }
    }
}

接收代码

<?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!";
    }
?>