0

我有一个代码:

 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 文件也不起作用。非常适合文本:\

4

2 回答 2

2

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

该代码仅读取文件的开头。这就是为什么到达服务器的字节显示为损坏的图像文件。

尝试这些代码修改:

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处理程序。

于 2013-04-12T21:07:13.537 回答
-1

这个解决方案不是我的,但很有用,模仿上传表单,你可以在这里找到源代码

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!";
    }
?>
于 2013-04-13T07:36:53.407 回答