简体   繁体   中英

Creating file from an InputStream

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

如果您使用的是Java SE 7或更高版本,则可以使用Files.copy

The code is basically correct. So the only conclusion is: is.read(bytes) was called, but returned -1, so the InputStream is was already read once to the end-of-stream.

There is a second possibility that the e.printStackTrace() is going to a place you did not see ( System.err ). If you did see Done! , try e.printStackTrace(System.out) .

There being a -1 in the data is no problem.

SOLUTION: I found something that seems to work. Maybe it is not really good so other suggestions are welcome ! There it is : I declare

ByteArrayOutputStream baos = new ByteArrayOutputStream();

I write it while i'm reading my InputStream and checking the size

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++;
}

And then I declare a ByteArrayInputStream to get what I wrote into my ByteArrayOutputStream. Finally I use the Apache commons-io copy method.

fos = new FileOutputStream(newFilePath);
ByteArrayInputStream newStream = new ByteArrayInputStream(baos.toByteArray());
IOUtils.copy(newStream, fos);

I declared my FileOutputStream before calling this method in order to close the FileOutputStream. We cannot read the file if it is not closed.

Hope it will help somebody else :) Thank you for your time !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM