I'm trying to copying a file given by the client into a temp file.
This given file is retrieved by my REST service into the InputStream.
Here is my code :
@POST
@Path("fileupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("uploadFormElement") InputStream uploadedInputStream,
@FormDataParam("uploadFormElement") FormDataContentDisposition fileDetail)
throws IOException {
Response.Status respStatus = Response.Status.OK;
if (fileDetail == null) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
} else {
if (uploadedInputStream != null) {
try {
initPath();
int size = 0;
int bytesRead;
boolean isStreamSizeCorrect = true;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((bytesRead = uploadedInputStream.read(buffer)) != -1) {
if (size > OntoWebStudioUtil.getUploadFileLimit()) {
isStreamSizeCorrect = false;
baos.close();
while ((bytesRead = uploadedInputStream.read(buffer)) != -1) {
size++;
}
break;
} else {
baos.write(buffer, 0, bytesRead);
}
size++;
}
if (!isStreamSizeCorrect) {
respStatus = Response.Status.NOT_ACCEPTABLE;
return Response
.status(respStatus)
.entity("Size of uploaded file exceeds the limit"
+ OWSConstants.UPLOAD_RESPONSE_VALUE_SEPARATOR
+ size).build();
}
byte[] outBuf = baos.toByteArray();
String newFilePath = "C:\\Docs\\my_pic.png";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newFilePath);
fos.write(outBuf);
}
catch (IOException e) {
e.printStackTrace(System.err);
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
e.printStackTrace(System.out);
}
}
}
return Response
.status(respStatus)
.entity(tempFileName
+ OWSConstants.UPLOAD_RESPONSE_VALUE_SEPARATOR
+ currentFileName).build();
}
}
The problem I have is that the file created in my temp directory is empty. I have to test the size of the file before creating it. That is the reason why I read my InputStream. So I tried to make a kind of copy of it during its reading. But it doesn't work. What can I do ?
Thanks