-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileUploader.java
More file actions
47 lines (40 loc) · 1.55 KB
/
FileUploader.java
File metadata and controls
47 lines (40 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package io.audd.example.utility;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FileUploader {
private static final int BufferSizeBytes = 2048;
private final String boundary;
private final File file;
private final String valueName;
FileUploader(File file, String boundary, String valueName) {
this.boundary = boundary;
this.valueName = valueName;
this.file = file;
}
long getContentLength() {
return (this.file.length() + ((long) getFileDescription().length())) + ((long) getBoundaryEnd().length());
}
String getFileDescription() {
return "\r\n--" + this.boundary + "\r\nContent-Disposition: form-data; name=\"" + this.valueName + "\"; filename=\"" + this.file.getName() + "\"\r\nContent-Type: %s\r\n\r\n";
}
private String getBoundaryEnd() {
return String.format("\r\n--%s--\r\n", new Object[]{this.boundary});
}
void writeTo(OutputStream outputStream) throws IOException {
outputStream.write(getFileDescription().getBytes("UTF-8"));
FileInputStream reader = new FileInputStream(this.file);
byte[] fileBuffer = new byte[2048];
while (true) {
int bytesRead = reader.read(fileBuffer);
if (bytesRead != -1) {
outputStream.write(fileBuffer, 0, bytesRead);
} else {
reader.close();
outputStream.write(getBoundaryEnd().getBytes("UTF-8"));
return;
}
}
}
}