use the -F
option of curl:
-F/--form <name=value> Specify HTTP multipart POST data
if there are multiple form fields, use multiple -F options.
for more details, refer to https://curl.haxx.se/docs/manpage.html#-F
example curl command line to upload a file:
curl -F “testFieldName=testFieldValue” -F “file=@/Users/zcai/Downloads/test_file.txt” –header “Authorization: Bearer your_token_string” http://hostname:port/webapp/rest/file/upload/testMethod
You can set any header information. The example above shows the Authorization token.
Java JAS-RS backend:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path(“/upload/testMethod“)
public Response uploadFile(MultipartFormDataInput multipart) {
InputStream is = null;
BufferedReader in = null;
String testFieldName = “”;
String fileName = “”;
try {
//get original file name, refer to https://stackoverflow.com/questions/26333298/multipartform-how-to-get-the-original-file-name
Map<String, List<InputPart>> formParts = multipart.getFormDataMap();
List<InputPart> inPart = formParts.get(“file”);
for (InputPart inputPart : inPart) {
MultivaluedMap<String, String> headers = inputPart.getHeaders();
String[] contentDispositionHeader = headers.getFirst(“Content-Disposition”).split(“;”);
for (String name : contentDispositionHeader) {
if ((name.trim().startsWith(“filename”))) {
String[] tmp = name.split(“=”);
fileName = tmp[1].trim().replaceAll(“\””,“”);
}
}
}
//get form file inputstream
is = multipart.getFormDataPart(“file”, InputStream.class, null);
in = new BufferedReader(new InputStreamReader(is));
//get form input field
testFieldName = multipart.getFormDataPart(“testFieldName“, String.class, null);
String line = in.readLine();
List<String> fileContent = new ArrayList<String>();
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return Response.ok().entity(fileName + ” has been uploaded to database successfully.\n”).build();
}