0

我正在尝试从我的 android 手机 (Samsung Galaxy s2) 上传 4.1.2 版的视频。

我已经配置了一个托管上传视频的 apache 服务器。我的问题如下:每次我从手机上传视频时,我都有一个损坏的文件。服务器上的文件比手机的文件少几个字节。它不是来自服务器,因为我使用 html 表单进行了一些测试,一切顺利。所以我想,它来自我的代码,但我不知道在哪里。有人可以帮助我吗,我已经花了几天的时间。

这是我的代码:@Override public boolean uploadFile() {

    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;

    String pathToOurFile = mMedia.getLocalPath();
    String urlServer = UploadConf.UPLOAD_SERVER;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";

    int bytesRead, bytesAvailable, bufferSize, totalBytesRead;
    byte[] buffer;
    int maxBufferSize = UploadConf.MAX_BUFFER_SIZE;

    try {
        File file = new File(pathToOurFile);
        FileInputStream fileInputStream = new FileInputStream(file);
        Log.i(LOG_TAG, "MediaUploader upload"  + file.getName() + " => "  +  file.getPath());

        Map<String, String> params = new HashMap<String, String>();
        params.put("mediaTitle", file.getName());

        URL url = new URL(urlServer + getFormattedParams(params));
        Log.i(LOG_TAG, "URL => " + urlServer + getFormattedParams(params));
        connection = (HttpURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setChunkedStreamingMode(UploadConf.CHUNK_SIZE);

        // 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=\"mediaFile\"" + lineEnd + lineEnd + file.getName() + lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"video_file\";filename=\"" + file.getName());
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytesRead = bytesRead;

        while (bytesRead > 0)
        {   
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            Log.i(LOG_TAG, "Progress " + totalBytesRead + " Read ");
            totalBytesRead += bytesRead;
            //outputStream.flush();
        }

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

        //Get Response  
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer(); 
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();


        // Responses from the server (code and message)
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        Log.d(LOG_TAG,"Server Response Code " + serverResponseCode);
        Log.d(LOG_TAG,"Server Response Message " + serverResponseMessage);

        Log.d(LOG_TAG,"Server Response " + response.toString());

        String result = response.toString();

        if (result == null || result.equals("")) {
            broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, fileInputStream, outputStream);
        }

        JSONObject json = null;
        try {
            json = new JSONObject(result);
        }
        catch (JSONException e) {
            Log.e(LOG_TAG, "Impossible to parse Json String");
            broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, fileInputStream, outputStream);
            return false;
        } 

        JSONObject jsonResult = json.getJSONObject(Constants.JSON_RESULT_TAG);

        if (jsonResult == null) {
            Log.e(LOG_TAG, "Json result is null ");
            broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, fileInputStream, outputStream);
            return false;
        }

        JSONArray errors;

        if (jsonResult.has(Constants.JSON_ERRORS_TAG)) {
            if ((errors = jsonResult.getJSONArray(Constants.JSON_ERRORS_TAG)) != null) {

                String notification = "";

                for (int i = 0; i < errors.length(); i++) {
                    JSONObject o = errors.getJSONObject(i);

                    notification +=  o.getString(Constants.JSON_ERROR_TAG);
                }
                broadcastIntent(notification, PRIORITY.ERROR, null, null);
                return false;
            }
        }

        mMedia.setSyncState(SyncState.SYNCED.ordinal());
        mMediaManager.updateMedia(mMedia);
        broadcastIntent(mContext.getString(R.string.upload_succeedeed_notification), PRIORITY.INFO, fileInputStream, outputStream);
        return true;
    } catch (UnknownHostException ex) {
        broadcastIntent(mContext.getString(R.string.upload_hostname_error_notification), PRIORITY.ERROR, null, null);
        Log.d(LOG_TAG, ex.getStackTrace().toString());
    } catch (Exception ex) {    
        broadcastIntent(mContext.getString(R.string.upload_failed_notification), PRIORITY.ERROR, null, null);
        Log.d(LOG_TAG,"Upload failed");
        ex.printStackTrace();
    }
    return false;
}
4

0 回答 0