1

I want to upload a file in struts1 application.

Currently the implementation is using File, like this:

<html:file property="upload"/>

But this does not allow to upload file if app is accessed from remote machine as this widget passes only the name of the file instead the whole file.

Alex K
  • 22,315
  • 19
  • 108
  • 236
user762421
  • 503
  • 1
  • 12
  • 24
  • File : html:file property="upload" - current impl – user762421 Nov 24 '11 at 10:08
  • 1
    You should not be interested in the file name, but in the file content. See also http://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3/3374408#3374408 Make it a `multipart/form-data` form. – BalusC Nov 24 '11 at 12:05
  • 1
    I'm not entirely sure what you mean; the file is available as a `FormFile` element in the `ActionForm`. Could you provide the code you believe doesn't work? – Dave Newton Nov 24 '11 at 19:17

1 Answers1

2

using only <html:file property="upload" /> will not make your application to upload a file.

to support upload functionality,your form must have enctype="multipart/form-data"

<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
File : <html:file property="upload" /> 
<br/`>

<html:submit />
</html:form`> 

and in action get file from your form bean and manipulate it as follows

YourForm uploadForm = (YourForm) form;
FileOutputStream outputStream = null;
FormFile file = null;
try {
  file = uploadForm.getFile();
  String path = getServlet().getServletContext().getRealPath("")+"/"+file.getFileName();
  outputStream = new FileOutputStream(new File(path));
  outputStream.write(file.getFileData());
}
finally {
  if (outputStream != null) {
    outputStream.close();
  }
}
Shahzad Badar
  • 114
  • 1
  • 3
  • 1
    Please do not save uploaded files in expanded WAR folder. They will all get lost whenever you redeploy the WAR or on some servers even when you restart the server (simply because they are not contained in the original WAR file!). Even more, when the server is configured to expand WAR in memory instead of on disk, then the `getRealPath()` would return `null` and everything will break. Just don't do that. Store them in a fixed disk file system location or at highest in a database instead. – BalusC Dec 01 '11 at 04:16