Uploading a file in struts1

2020-07-27 05:56发布

问题:

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.

回答1:

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();
  }
}