android - 如何在android中拆分InputStream/OutPutStream

标签 android file-upload io inputstream

我正在将一个流上传到服务器。但是我的Input-stream包含一个大视频文件。所以我想将其拆分为不同的输入流,然后我将它们一一发送。

我在Java中解决了一个问题,即TeeOutputStream(我不知道它在java中是如何工作的),但它在android中不存在。 像往常一样,任何帮助都非常感谢

已更新

请不要建议我手动方式。

最佳答案

您不必拆分输入或输出流。 您可以使用多部分实体上传大文件。在多部分实体中有一个类 FileEntity 负责上传文件

我有一个多部分实体的代码,请参阅下面的代码。

public class uploadFile extends AsyncTask<Void, Void, Boolean> {
        private final ProgressDialog dialog = new ProgressDialog(parentActivity);

        protected void onPreExecute() {
            this.dialog.setMessage("Uploading file");
            this.dialog.setCancelable(false);
            this.dialog.show();
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {

            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(URLS.PRESCRIPTION_POST_URL);
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                reqEntity.addPart("title", new StringBody("This is a title of video file"));
                try {
                    File f = new File(Environment.getExternalStorageDirectory(), "your file name with extension");

                    FileBody body = new FileBody(f);
                    reqEntity.addPart("parameter that server will read", body);

                } catch (Exception e) {
                    reqEntity.addPart("parameter that server will read", new StringBody(""));
                }

                reqEntity.addPart("description", new StringBody("description"));

                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);

                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
                String sResponse; StringBuilder s = new StringBuilder(); 
                while ((sResponse = reader.readLine()) != null) { 
                    s = s.append(sResponse); 
                } 
                Log.v("Response for POst", s.toString());
                return true;
            } catch (Exception e) {
                Log.e("MyPharmacyOptions", "Error :: " + e);
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
            if (result) {
                Toast.makeText(parentActivity,
                        "File uploaded successfully", Toast.LENGTH_LONG)
                        .show();

            } else {
                Toast.makeText(parentActivity, "Your Request not complete",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

要使用 MultipartEntity,您需要一个 jar 文件 httpmime-4.1.2.jar

还有另一种选择

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

String pathToOurFile = "/sdcard/file_to_send.mp3"; //complete path of file from your android device
String urlServer = "URL of your server";// complete path of server
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

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

byte []buffer = new byte[4096];
int read = 0;
while ( (read = fileInputStream.read(buffer)) != -1 ) {
    outputStream.write(buffer, 0, read);
}

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
}

关于android - 如何在android中拆分InputStream/OutPutStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9886556/

相关文章:

android - OpenCV Android - 人像模式下的精致相机

curl - Laravel 5.1 AWS S3 Flysytem : AWS HTTP error: cURL error 6: Couldn't resolve host name

jquery - 网络摄像头图片直接保存到文件附件

c# - 如何检查文件锁定?

java - Android:将 gson.toJson() 返回字符串保存在我的 SD 卡上

android - getQuantityString 没有用值替换格式

java - RecycleView 分页最后没有添加新项目?

jquery - HTML5 : How to count the length of the files from the multiple-input field

c++ - C++ 中的流式 I/O

安卓位置监听器