【问题标题】:how to split an InputStream/OutPutStream in android如何在 android 中拆分 InputStream/OutPutStream
【发布时间】:2012-04-10 19:24:03
【问题描述】:

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

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

更新

请不要建议我手动方式。

【问题讨论】:

    标签: android file-upload io inputstream


    【解决方案1】:

    您不必拆分输入或输出流。 您可以上传带有多部分实体的大文件。在多部分实体中有一个类 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
    }
    

    【讨论】:

    • +1 @Dharmendra。虽然它不能回答我的问题,但很努力
    • @Sameer - 你找到问题的答案了吗?
    • @Sameer,您要拆分流并同时上传吗?如果是这样,您的服务器需要处理同时流。如果您一次只对一个流感兴趣,那么您可以参考上面的答案,因为这是将您的文件上传到字节块中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2011-05-05
    • 2011-01-06
    • 2018-02-25
    • 2012-08-03
    • 2012-04-30
    相关资源
    最近更新 更多