This question concerns file handling using Java/Groovy/Grails. I am still new to these technologies, so bear with me.
I am uploading a file to Stripe after receiving the file from a user submitted POST request from the client side. I don't want to save it to the disk if it can be avoided.
I receive the file and parse into an array of bytes.
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getMultiFileMap().collect {
it.value
}.flatten()
try {
if (files.size > 0) {
// parse file and get byte array input stream
MultipartFile file = files.first()
String fileName = file.originalFilename
byte[] bytes = file.inputStream.getBytes()
callStripeFileService(bytes)
}
This byte array is passed to a service which makes the call to Stripe as indicated in their docs.
callStripeFileService(byte[] bytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes)
String tempFilePath =
"src/main/resources/tmp/${fileName}"
IOUtils.copy(bais, new FileOutputStream(tempFilePath))
FileCreateParams params = FileCreateParams.builder()
.setFile(new java.io.File(tempFilePath))
.setPurpose(FileCreateParams.Purpose.RECEIPT)
.build()
File upload = File.create(params)
}
This is working just fine, but I dislike writing the file to disk only to have to remove it eventually. I also suspect that there must be performance implications to writing to disk.
I would love to just pass a stream to Stripe, but the .setFile()
method only accepts a File or FileInputStream.
Is there any way to create a valid Java File object without saving anything to disk?
question from:
https://stackoverflow.com/questions/65621408/convert-bytearrayinputstream-to-file-without-saving-to-disk 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…