0

I need to read a MS-Excel (.xlsx) within my Spring MVC app, edit it and send it to the user on demand. Locally on my development station, I use

String path = "c:/dev/workspace/SCF-trend/web/WEB-INF/files/";
File template = new File(path + "trendline-template.xlsx");

But once I deploy this app, I loose the path.

How can I do it so the application understand the path?

I tried to use the ServletContext approach provided as an answer on the following question here, but it didn't work.

Spring MVC Get file under WEB-INF without a request

How can I solve this? Ideas are most welcome!

Community
  • 1
  • 1
gtludwig
  • 5,411
  • 10
  • 64
  • 90

1 Answers1

1

If it's a webapp resource, just get it as webapp resource instead by ServletContext#getResourceAsStream().

InputStream input = servletContext.getResourceAsStream("/WEB-INF/files/trendline-template.xlxs");
// ...

Never use java.io.File and friends on deploy folder. This is recipe for portability trouble and disaster.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • thanks! I failed to mention a mid step on my question. My original approach using java.io.File was to duplicate the file and edit, save and download the copied. Can you thown me some pointers on that as well? I know I need an OutputStream to save the file, but ServletContext doesn't offer a .setResourceAsStream("") method... – gtludwig Jul 16 '13 at 13:55
  • Do you absolutely need to save the edited file on local disk file system? Isn't the sole intent to open it, edit it and then immediately write it to response for download without saving the edited version on disk? Surely you can feed POI an `InputStream` and tell it to write to `response.getOutputStream()`. If you absolutely need to save it, then save it to a fixed path outside the deploy folder by the usual Java IO means. Do absolutely not write to deploy folder. Everything get lost once you redeploy the WAR, for the simple reson that those changes are not contained in the original WAR file. – BalusC Jul 16 '13 at 14:05
  • Well, actually no. As long as I could generate the file on a post method call on a button and download on a get method call on another, I should be fine. – gtludwig Jul 16 '13 at 14:08
  • You could either store it in session (and remove it on download call!) or use `File#createTempFile()` to save it as temp file. Or, you could just immediately write the download to response of the POST call so that the enduser doesn't need to fire another request thereafter (and you don't need to fiddle around with temporary storage). – BalusC Jul 16 '13 at 14:09