Skip to content

Commit 5cc8afd

Browse files
authored
Merge pull request #954 from PlayerData/upload-channel
Switch to using channels for byte copying.
2 parents 58e50a2 + d8c51cc commit 5cc8afd

File tree

1 file changed

+23
-13
lines changed

1 file changed

+23
-13
lines changed

android/src/main/java/com/rnfs/Uploader.java

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
import java.io.FileInputStream;
1717
import java.io.InputStreamReader;
1818
import java.net.HttpURLConnection;
19+
import java.nio.channels.Channels;
20+
import java.nio.channels.FileChannel;
21+
import java.nio.channels.WritableByteChannel;
1922
import java.util.List;
2023
import java.util.Map;
2124
import java.util.concurrent.atomic.AtomicBoolean;
@@ -126,39 +129,46 @@ private void upload(UploadParams params, UploadResult result) throws Exception {
126129
connection.connect();
127130

128131
request = new DataOutputStream(connection.getOutputStream());
132+
WritableByteChannel requestChannel = Channels.newChannel(request);
133+
129134
if (!binaryStreamOnly) {
130135
request.writeBytes(metaData);
131136
}
132137

133138
byteSentTotal = 0;
134-
Runtime run = Runtime.getRuntime();
135139

136140
for (ReadableMap map : params.files) {
137141
if (!binaryStreamOnly) {
138142
request.writeBytes(fileHeader[fileCount]);
139143
}
144+
140145
File file = new File(map.getString("filepath"));
141-
int fileLength = (int) file.length();
142-
int bytes_read = 0;
143-
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
144-
int buffer_size =(int) Math.ceil(fileLength / 100.f);
145-
if(buffer_size > run.freeMemory() / 10.f) {
146-
buffer_size = (int) Math.ceil(run.freeMemory() / 10.f);
147-
}
148-
byte[] buffer = new byte[buffer_size];
149-
while ((bytes_read = bufInput.read(buffer)) != -1) {
150-
request.write(buffer, 0, bytes_read);
146+
147+
long fileLength = file.length();
148+
long bufferSize = (long) Math.ceil(fileLength / 100.f);
149+
long bytesRead = 0;
150+
151+
FileInputStream fileStream = new FileInputStream(file);
152+
FileChannel fileChannel = fileStream.getChannel();
153+
154+
while (bytesRead < fileLength) {
155+
long transferredBytes = fileChannel.transferTo(bytesRead, bufferSize, requestChannel);
156+
bytesRead += transferredBytes;
157+
151158
if (mParams.onUploadProgress != null) {
152-
byteSentTotal += bytes_read;
159+
byteSentTotal += transferredBytes;
153160
mParams.onUploadProgress.onUploadProgress((int) totalFileLength, byteSentTotal);
154161
}
155162
}
163+
156164
if (!binaryStreamOnly) {
157165
request.writeBytes(crlf);
158166
}
167+
159168
fileCount++;
160-
bufInput.close();
169+
fileStream.close();
161170
}
171+
162172
if (!binaryStreamOnly) {
163173
request.writeBytes(tail);
164174
}

0 commit comments

Comments
 (0)