So I am trying to do, what I thought, was a simple file read and import. So the way my code works now is that I have a file stored in a folder on the server, select it, and import it. I select the file through a multipartfile:
<g:form method="post" enctype="multipart/form-data" controller="fileManager">
<label>Company Name:</label><input id="cname" type="text" name="cname" /><br />
<label>Select a CSV file to upload:</label> <input type="file" id="newFile" name="newFile" />
<g:actionSubmit action="importContactsFromFile" value="Import" />
</g:form>
So what I want to do is to:
- Have user select a file
- Download the file to a directory on the server (input/output stream?)
- Read the file contents (CSVReader) and import into DB (this works)
- Possibly clean up file after
So I have a massive headache with that second step. I pull the file into a def variable:
def newFile = request.getFile('newFile')
How do I bridge this gap? Slamming my head over this! Thanks!
Do you need to save the file as an intermediate step before parsing it? Most CSV parsers (OpenCSV for example) will read from a
ReaderorInputStreamdirectly. So you can do something like:If you want to save the file, you can use the
transferTomethod:In that case, you’ll have to ensure two requests don’t overwrite each other by ensuring unique a file name.
You can find more information in the grails manual: http://grails.org/doc/latest/guide/theWebLayer.html#6.1.9%20Uploading%20Files