File Upload in Struts2 frame: _struts

Source: Internet
Author: User

To define a form:

<input type= "file" name= "upload" method= "post" enctype= "Multipart/form-data"/>

Define the Action property that receives the form

/* struts2 frame File Upload:
* file conditions:
* Form submission needs to be a post * The
upload item must have a name attribute in the form.
The form's Enctype property value needs to be
the three attributes required for multipart/form-data*///file uploads: Public
class fileaction{
	//upload must be the same as the form name
    private File upload;
    Private String uploadfilename;
    Private String Uploadcontenttype;

    public void Setupload (File upload) {
        this.upload = upload;
    }

    public void Setuploadfilename (String uploadfilename) {
        this.uploadfilename = uploadfilename;
    }

    public void Setuploadcontenttype (String uploadcontenttype) {
        this.uploadcontenttype = Uploadcontenttype;
    }
}

Define the method to receive the action, the idea to define this action in the struts file, and the path that defines the intercept in the Web.xml

Import Org.apache.commons.io.FileUtils;
    The public String Save () throws IOException {
        //adds the submitted data to the database. Product is the received class
        Product.setpdate (New Date ());
        Product.setimage (image);
        if (upload!= null) {
            //upload the merchandise picture to the server.
            Get the server-side path to the uploaded picture.
            String path = Servletactioncontext.getservletcontext (). Getrealpath (
                    "/products");
            To create a file type object: File
            diskfile = new File (path + "//" + uploadfilename);
            File Upload:
            fileutils.copyfile (upload, diskfile);
    
            Product.setimage ("products/" + uploadfilename);
        }
        Productservice.save (product);
        return "savesuccess";
    }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.