Skip to content

Commit 97dcd27

Browse files
committed
upload a file with okhttp
1 parent f973292 commit 97dcd27

File tree

8 files changed

+162
-2
lines changed

8 files changed

+162
-2
lines changed

Book-RESTful-Service/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,5 @@ This RESTful ws provides API for all below sub projects:
2626
###[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/)
2727
###[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/)
2828
###[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/)
29-
###[Java REST Client Using Retrofit 2](http://howtoprogram.xyz/2016/10/17/java-rest-client-using-retrofit-2/)
29+
###[Java REST Client Using Retrofit 2](http://howtoprogram.xyz/2016/10/17/java-rest-client-using-retrofit-2/)
30+
###[Upload a File with OkHttp](http://howtoprogram.xyz/2016/11/21/upload-file-okhttp/)
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.howtoprogram.book;
2+
3+
import java.util.Iterator;
4+
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.http.HttpStatus;
7+
import org.springframework.http.ResponseEntity;
8+
import org.springframework.web.bind.annotation.RequestMapping;
9+
import org.springframework.web.bind.annotation.RequestMethod;
10+
import org.springframework.web.bind.annotation.RequestParam;
11+
import org.springframework.web.bind.annotation.RestController;
12+
import org.springframework.web.multipart.MultipartFile;
13+
import org.springframework.web.multipart.MultipartHttpServletRequest;
14+
15+
import com.howtoprogram.service.StorageService;
16+
17+
@RestController
18+
@RequestMapping(value = "/v1")
19+
public class FileUploadController {
20+
21+
@Autowired
22+
private StorageService storageService;
23+
24+
@RequestMapping(value = "/upload", method = RequestMethod.POST)
25+
public ResponseEntity uploadFile(@RequestParam(value = "file") MultipartFile multipartFile) {
26+
// stores the file to disk
27+
storageService.store(multipartFile);
28+
return new ResponseEntity<>("{}", HttpStatus.OK);
29+
}
30+
31+
@RequestMapping(value = "/uploads", method = RequestMethod.POST)
32+
public ResponseEntity uploadFile(MultipartHttpServletRequest request) {
33+
34+
try {
35+
Iterator<String> itr = request.getFileNames();
36+
while (itr.hasNext()) {
37+
String uploadedFile = itr.next();
38+
MultipartFile file = request.getFile(uploadedFile);
39+
String mimeType = file.getContentType();
40+
String filename = file.getOriginalFilename();
41+
byte[] bytes = file.getBytes();
42+
System.out.println(mimeType);
43+
System.out.println(filename);
44+
45+
}
46+
} catch (Exception e) {
47+
return new ResponseEntity<>("{}", HttpStatus.INTERNAL_SERVER_ERROR);
48+
}
49+
50+
return new ResponseEntity<>("{}", HttpStatus.OK);
51+
}
52+
53+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.howtoprogram.service;
2+
3+
import java.io.IOException;
4+
import java.nio.file.Files;
5+
import java.nio.file.Path;
6+
import java.nio.file.Paths;
7+
8+
import org.springframework.stereotype.Service;
9+
import org.springframework.web.multipart.MultipartFile;
10+
11+
@Service
12+
public class FileSystemStorageService implements StorageService {
13+
private final Path rootLocation = Paths.get(".");
14+
15+
@Override
16+
public void store(MultipartFile file) {
17+
try {
18+
if (file.isEmpty()) {
19+
throw new StorageException(
20+
"Failed to store empty file " + file.getOriginalFilename());
21+
}
22+
Files.copy(file.getInputStream(),
23+
this.rootLocation.resolve(file.getOriginalFilename()));
24+
} catch (IOException e) {
25+
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
26+
}
27+
}
28+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.howtoprogram.service;
2+
3+
public class StorageException extends RuntimeException {
4+
5+
public StorageException(String message) {
6+
super(message);
7+
}
8+
9+
public StorageException(String message, Throwable cause) {
10+
super(message, cause);
11+
}
12+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.howtoprogram.service;
2+
3+
import org.springframework.web.multipart.MultipartFile;
4+
5+
public interface StorageService {
6+
7+
void store(MultipartFile file);
8+
9+
}

okhttp-examples/pom.xml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@
2020
<artifactId>okhttp</artifactId>
2121
<version>3.4.1</version>
2222
</dependency>
23-
23+
<dependency>
24+
<groupId>junit</groupId>
25+
<artifactId>junit</artifactId>
26+
<version>4.8.1</version>
27+
<scope>test</scope>
28+
</dependency>
2429
</dependencies>
2530
</project>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.howtoprogram.okhttp.upload;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
6+
import okhttp3.MediaType;
7+
import okhttp3.MultipartBody;
8+
import okhttp3.OkHttpClient;
9+
import okhttp3.Request;
10+
import okhttp3.RequestBody;
11+
import okhttp3.Response;
12+
13+
public class UploadService {
14+
15+
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
16+
17+
public void uploadImage(File image, String imageName) throws IOException {
18+
19+
OkHttpClient client = new OkHttpClient();
20+
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
21+
.addFormDataPart("file", imageName, RequestBody.create(MEDIA_TYPE_PNG, image))
22+
.build();
23+
24+
Request request = new Request.Builder().url("http://localhost:8080/v1/upload")
25+
.post(requestBody).build();
26+
27+
Response response = client.newCall(request).execute();
28+
if (!response.isSuccessful()) {
29+
throw new IOException("Unexpected code " + response);
30+
}
31+
32+
}
33+
34+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.howtoprogram.okhttp.upload;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
6+
import org.junit.Test;
7+
8+
public class UploadServiceTest {
9+
10+
@Test
11+
public void testUploadImage() throws IOException {
12+
File file = new File("d:\\Tmp\\abc.png");
13+
UploadService uploadService = new UploadService();
14+
uploadService.uploadImage(file, "abc.png");
15+
16+
}
17+
18+
}

0 commit comments

Comments
 (0)