Reputation: 8033
I'm working on a spring mvc application. at this time i need to have action for file downloading. due to this post my controller's action now is like this:
@RequestMapping(value = "/file/{id}", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getFile(@PathVariable("id") int id, HttpServletResponse response) throws FileNotFoundException {
//fetch file record from database
Files file = orchService.fileFind(id);
//directory of the file is based on file ID(this is not important in this question)
InputStream inputStream = new FileInputStream(myFileDirectory);
response.setHeader("Content-Disposition", "attachment; filename=\"filename " + file.getId() + "."+file.getExtension()+"\"");
int read=0;
byte[] bytes = new byte[];
//remaining of code
}
my problem is on the bytes
declaration. file
has a long getSize()
method that return the size of the files. but i can't use byte[] bytes = new byte[file.getSize()];
, because the array size must be an integer value. how can i solve this problem?
I don't want to copy whole file into memory.
Upvotes: 1
Views: 1345
Reputation: 57381
Use IOUtils and just copy streams (file stream to response stream)
copy(InputStream input, OutputStream output)
Copies bytes from an InputStream to an OutputStream.
copy(InputStream input, OutputStream output, int bufferSize)
Copies bytes from an InputStream to an OutputStream using an internal buffer of the given size.
Upvotes: 2
Reputation: 602
Read your data in a loop with a buffer of bytes. Reading to large byte arrays could be a performance issue.
If you need to save the data use a file or stream.
Reading a binary input stream into a single byte array in Java
Upvotes: 1