PUT with a binary file

3,183 views
Skip to first unread message

Olexij Tkatchenko

unread,
Apr 7, 2015, 3:50:09 PM4/7/15
to spar...@googlegroups.com
Hi, I'm stuck while figuring out, how to define a PUT route with a binary file. Currently I have:

endpoint:

put(API_CONTEXT + "/sounds/:id/record", "audio/wav", (request, response)
-> soundService.uploadRecord(request.params(":id"), request), new JsonTransformer());


processing:

public Object uploadRecord(String params, Request request) {
HttpServletRequest httpRequest = request.raw();
try {
InputStream body = httpRequest.getInputStream();

// stream length is zero!
int streamLength = body.available();
byte[] targetArray = new byte[streamLength];
body.read(targetArray);
InputStream is = new ByteArrayInputStream(targetArray);
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

test call:


When I try to send a PUT call with a binary file I get no data (stream length is zero) on the SparkJava service site. How to do that properly?

Olexij Tkatchenko

unread,
Apr 10, 2015, 2:43:59 AM4/10/15
to spar...@googlegroups.com

I figured out how to do a post of a binary file with using of apache.commons and using a POST request. The relevant code part is:

    public Object uploadRecord(String id, Request sparkRequest) {
HttpServletRequest request = sparkRequest.raw();
boolean isMultipart=ServletFileUpload.isMultipartContent(request);

// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);

FileItem item = items.get(0);
try {
String fileName = item.getName();
if(fileName != null) {
File uploadedFile = File.createTempFile(fileName, ".tmp");

item.write(uploadedFile);

  // Do your stuff with uploaded temporary file

                }
} catch (Throwable e) {
e.printStackTrace();
}

} catch (FileUploadException e) {
e.printStackTrace();
}


return null;
}

The curl call is:


Gustavo Galvan

unread,
May 11, 2015, 7:17:45 AM5/11/15
to spar...@googlegroups.com
You can skip using apache.commons for multipart forms. 
See this example:

post("/upload", "multipart/form-data", (request, response) -> {
//- Servlet 3.x config
String location = "/aaa/bbb";  // the directory location where files will be stored
long maxFileSize = 100000000;  // the maximum size allowed for uploaded files
long maxRequestSize = 100000000;  // the maximum size allowed for multipart/form-data requests
int fileSizeThreshold = 1024;  // the size threshold after which files will be written to disk
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(location, maxFileSize, maxRequestSize, fileSizeThreshold);
request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
//-/
Collection<Part> parts = request.raw().getParts();
for(Part part : parts) {
System.out.println("Name:");
System.out.println(part.getName());
System.out.println("Size: ");
System.out.println(part.getSize());
System.out.println("Filename:");
System.out.println(part.getSubmittedFileName());
}
String fName = request.raw().getPart("upfile").getSubmittedFileName();
System.out.println("Title: "+request.raw().getParameter("title"));
System.out.println("File: "+fName);
Part uploadedFile = request.raw().getPart("upfile");
Path out = Paths.get("/aaa/bbb/"+fName);
try (final InputStream in = uploadedFile.getInputStream()) {
Files.copy(in, out);
uploadedFile.delete();
}
// cleanup
multipartConfigElement = null;
parts = null;
uploadedFile = null;
return "OK";
});

, and the html form:

<!DOCTYPE html>
<html><head><title>Upload form</title></head>
<body>
<h3>Upload form</h3>
<form action="/upload" enctype="multipart/form-data" method="post">
<label for="title">Title</label>
<input type="text" name="title"><br>
<label for="upfile">File to send</label>
<input type="file" name="upfile"><br>
<input type="submit" value="Upload">
</form>
</body>
</html>
Reply all
Reply to author
Forward
0 new messages