Как разделить InputStream / OutPutStream в Android - PullRequest
2 голосов
/ 27 марта 2012

Я загружаю поток на сервер. Но мои Input-stream содержат большой видеофайл. Поэтому я хочу разделить его на другой поток ввода, а затем я отправлю их один за другим.

Iпрошли через вопрос, что TeeOutputStream (я не знаю, как это работает в Java) в Java для этого. Но он не существует в Android.Любая помощь высоко ценится как обычно

Обновлено

Пожалуйста, не предлагайте мне ручной способ.

1 Ответ

2 голосов
/ 27 марта 2012

Вам не нужно разделять входной или выходной поток. Вы можете загрузить большой файл с составной сущностью. В составной сущности есть класс 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
}
...