简体   繁体   中英

Android NDK: File Upload using NDK

Is there any source code for uploading a file from SD to a server using NDK? or any other method to upload a large size file without getting

Out Of Memory Exception

if so plz provide me the link?

The Code below is the one which i used and i got Out Of Memory Exception

 private void UploadFileByClient(LocalFileVO localFileVO){


        try{

            File uploadFile = new File(
                    (localFileVO.getFolderPath() + "/" + localFileVO.getFileName()));

            HttpClient    client = new DefaultHttpClient();

            final HttpResponse resp; 
            final HttpClient httpClient = new DefaultHttpClient(); 
            final HttpPut post = new HttpPut("https://qa2-talos-vip-mexico.symnds.com/fileservice/files/");
            post.setHeader("User-Agent", "Mexico/1.0.0.57/android");
            post.setHeader("Content-Type", localFileVO.getMimeType());
            post.setHeader("Authorization", TOKEN);
            post.setHeader("x-mexico-endpointid", GUID);
            post.setHeader("x-mexico-filehash", localFileVO.getFileHash());
            post.setHeader("x-mexico-filesize", localFileVO.getSize());

            if (!TextUtils.equals("0", localFileVO.getFolderId()))
                post.setHeader("x-mexico-folder", localFileVO.getFolderId());

            post.setHeader("x-mexico-filename", localFileVO.getEncodedFileName());
            post.setHeader("Expect", "100-continue");
            post.setHeader("x-mexico-modtime",
                    String.valueOf(System.currentTimeMillis() / 1000));



//          ParcelFileDescriptor fileDescriptor = this.getContentResolver().openFileDescriptor(Uri.parse(uploadFile.getAbsolutePath()), "r"); 
//          InputStream in = this.getContentResolver().openInputStream(Uri.parse(uploadFile.getAbsolutePath()));
            InputStream in = new FileInputStream(uploadFile);

            CountingInputStreamEntity entity = new CountingInputStreamEntity(in, uploadFile.length()); 
            entity.setUploadListener(this);
            post.setEntity(entity); 
            resp = httpClient.execute(post); 
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 
                System.out.println("=======================Got the response from server============================");
            }


        }catch(Exception e){
            System.out.println("==============Failed using HttpClient================="+e.getMessage());
        }

    }

   private int uploadFile( LocalFileVO localFileVO) throws IOException {


       UploadFileByClient(localFileVO);

      if(true){
          return 0;
      }

        File uploadFile = new File((localFileVO.getFolderPath() + "/" + localFileVO.getFileName()));


        System.setProperty("http.keepAlive", "false");

        int     code = 0;
        try{

        HttpURLConnection urlConnection; 

        URL url = new URL("https://qa2-talos-vip-mexico.symnds.com/fileservice/files/");
    //  URL url = new URL("https://zpi.nortonzone.com/fileservice/files/");

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(30000);
        urlConnection.setRequestProperty("Host", url.getHost());
        // urlConnection.setRequestProperty("Connection", "Keep-Alive");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setInstanceFollowRedirects(false);
    //  urlConnection.setChunkedStreamingMode(1024);
        urlConnection.setFixedLengthStreamingMode(Integer.parseInt(localFileVO.getSize()));
        //urlConnection.setChunkedStreamingMode(1024);

        urlConnection.setRequestMethod("PUT");
        urlConnection.setRequestProperty("User-Agent", "Mexico/1.0.0.57/android");
        urlConnection.setRequestProperty("Content-Type", localFileVO.getMimeType());
        //urlConnection.setRequestProperty("Content-Length", localFileVO.getSize());
        urlConnection.setRequestProperty("Authorization", TOKEN);
        urlConnection.setRequestProperty("x-mexico-endpointid", GUID);
        urlConnection.setRequestProperty("x-mexico-filehash", localFileVO.getFileHash());
        //urlConnection.setRequestProperty("x-mexico-filesize", localFileVO.getSize());

        if (!TextUtils.equals("0", localFileVO.getFolderId()))
            urlConnection.setRequestProperty("x-mexico-folder", localFileVO.getFolderId());

        urlConnection.setRequestProperty("x-mexico-filename", localFileVO.getEncodedFileName());
        urlConnection.setRequestProperty("Expect", "100-continue");
        urlConnection.setRequestProperty("x-mexico-modtime",
                String.valueOf(System.currentTimeMillis() / 1000));

        bufferOutputStream = new BufferedOutputStream(urlConnection.getOutputStream(),BSIZE);
    //  CountingOutputStream cOutStream = new CountingOutputStream(bufferOutputStream);

        FileInputStream fileInputStream = new FileInputStream(uploadFile);

        long startTime = System.currentTimeMillis();
        try{
            int totalSize = 0;

             while (true) {
                   synchronized (chunks) {
                        int amountRead = fileInputStream.read(chunks);
                        System.out.println("========amount read========="+amountRead);
                        if (amountRead == -1) {
                              break;
                        }
                        bufferOutputStream.write(chunks, 0, amountRead);
                        bufferOutputStream.flush();
                  }
             }
            System.out.println("================================TotalSize " + totalSize);
            bufferOutputStream.flush();
             bufferOutputStream.close();
             fileInputStream.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        long endTime = System.currentTimeMillis();
        System.out.println("=============================================Writing time ==========================================================" + (endTime - startTime)); 
        //code = urlConnection.getResponseCode();

        InputStream inputStream  = urlConnection.getInputStream();



    long endTime1 = System.currentTimeMillis();
    System.out.println("Time to get the response is  " + (endTime1 - endTime)); 
    // progressBar.setProgress(100);
        System.out.println("=================Response code is ================="+code);
        urlConnection.disconnect();
        //fileInputStream.close();

        }catch(Exception e){
            System.out.println("========================Exception occured=================="+e.getMessage());
        }
        return code;

    }

Thank u

Your don't need NDK for this. Without your code I can only suggest that there are code for reading whole file into buffer. It is wrong. Do something like: read files by small parts and sent these parts one by one into output stream (get it from connection)

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

Seems you missed setChunkedStreamingMode(int) call from:http://developer.android.com/reference/java/net/HttpURLConnection.html Posting Content To upload data to a web server, configure the connection for output using setDoOutput(true). For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

But your content is too big to be buffered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM