|
20 | 20 | import com.google.api.services.storage.model.Objects; |
21 | 21 | import com.google.api.services.storage.model.StorageObject; |
22 | 22 |
|
23 | | -import java.io.ByteArrayInputStream; |
| 23 | +import java.io.File; |
| 24 | +import java.io.FileInputStream; |
24 | 25 | import java.io.IOException; |
25 | | -import java.io.InputStream; |
| 26 | +import java.nio.file.Files; |
| 27 | +import java.nio.file.Path; |
26 | 28 | import java.security.GeneralSecurityException; |
27 | 29 | import java.util.ArrayList; |
28 | 30 | import java.util.Arrays; |
@@ -91,13 +93,16 @@ public static Bucket getBucket(String bucketName) throws IOException, GeneralSec |
91 | 93 | * |
92 | 94 | * @param name the name of the destination object. |
93 | 95 | * @param contentType the MIME type of the data. |
94 | | - * @param stream the data - for instance, you can use a FileInputStream to upload a file. |
| 96 | + * @param file the file to upload. |
95 | 97 | * @param bucketName the name of the bucket to create the object in. |
96 | 98 | */ |
97 | | - public static void uploadStream( |
98 | | - String name, String contentType, InputStream stream, String bucketName) |
| 99 | + public static void uploadFile( |
| 100 | + String name, String contentType, File file, String bucketName) |
99 | 101 | throws IOException, GeneralSecurityException { |
100 | | - InputStreamContent contentStream = new InputStreamContent(contentType, stream); |
| 102 | + InputStreamContent contentStream = new InputStreamContent( |
| 103 | + contentType, new FileInputStream(file)); |
| 104 | + // Setting the length improves upload performance |
| 105 | + contentStream.setLength(file.length()); |
101 | 106 | StorageObject objectMetadata = new StorageObject() |
102 | 107 | // Set the destination object name |
103 | 108 | .setName(name) |
@@ -161,11 +166,13 @@ public static void main(String[] args) { |
161 | 166 | } |
162 | 167 |
|
163 | 168 |
|
164 | | - // Upload a stream to the bucket. This could very well be a file. |
165 | | - uploadStream( |
166 | | - TEST_FILENAME, "text/plain", |
167 | | - new ByteArrayInputStream("Test of json storage sample".getBytes()), |
168 | | - bucketName); |
| 169 | + // Create a temp file to upload |
| 170 | + Path tempPath = Files.createTempFile("StorageSample", "txt"); |
| 171 | + Files.write(tempPath, "Sample file".getBytes()); |
| 172 | + File tempFile = tempPath.toFile(); |
| 173 | + tempFile.deleteOnExit(); |
| 174 | + // Upload it |
| 175 | + uploadFile(TEST_FILENAME, "text/plain", tempFile, bucketName); |
169 | 176 |
|
170 | 177 | // Now delete the file |
171 | 178 | deleteObject(TEST_FILENAME, bucketName); |
|
0 commit comments