Formfile for file upload in struts
1. Defining in a JSP file
<form action= "/strutsfileupanddown/register.do" method= "post" enctype= "Multipart/form-data" > name:< Input type= "text" name= "name"/> head: <input type= "file" name= "file"/> <input type= "Submit" value= " Registered users "> </form>
2. Define the Formfile in the form form
/* * Generated by MyEclipse Struts * Template path:templates/java/javaclass.vtl */package Com.yourcompany.struts.form;im Port Javax.servlet.http.httpservletrequest;import Org.apache.struts.action.actionform;import Org.apache.struts.action.actionmapping;import org.apache.struts.upload.formfile;/** * MyEclipse struts * Creation date:08-24-2017 * * XDoclet definition: * @struts. Form name= "UserForm" */public class UserForm extends Actio Nform {/* * Generated Methods */private string username;private formfile file;public string GetUserName () {return username ;} public void Setusername (String username) {this.username = username;} Public Formfile GetFile () {return file;} public void Setfile (formfile file) {this.file = file;}}
3. Use the struts file to correlate the form and later
1) Using the form instance to obtain Formfile instance, after obtaining, we can obtain the various information which uploads the file through the Formfile
UserForm UserForm = (UserForm) Form; String username = userform.getusername (); Formfile file = Userform.getfile ();//through Formfile can get various information about user upload file//To get the file name string fileName = File.getfilename ();// Used to get the file size int fileSize = File.getfilesize ();
2) get the input stream through the Formfile instance, create an output stream, and get the absolute path to the Tomcat server in your code
try {//Get input stream is = File.getinputstream ();//Get output stream//1. Get the file folder, the absolute path after uploading to the Tomcat server (file file is the newly created folder) String FilePath = This.getservlet (). Getservletcontext (). Getrealpath ("/file");//One of the two "//" is an escape character os=new FileOutputStream (FilePath + "\ \" +filename); int len=0;//Reads bytes//makes a cache, prevents file too large and causes errors byte[] buff=new byte[1024];while ((Len=is.read (Buff))!=-1) {Os.write (buff,0, Len);} Is.close (); Os.close (); }
Struts file Upload (formfile)