Uploading a file in struts1

2020-07-27 06:02发布

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条回答
来,给爷笑一个
2楼-- · 2020-07-27 06:20

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();
  }
}
查看更多
登录 后发表回答