27 August 2017

Struts 2 Framework: Update File với Struts Java web


fileupload.jsp
Java 2017
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
    <head>
        <title>file upload page</title>
    </head>
    <body>
    <s:form action="fileUpload" method="post" enctype="multipart/form-data">
        <s:file name="photo" label="Choose file to upload" />
        <s:submit value="upload" align="center" />
    </s:form>
</body>
</html>
actionProduct.java
Java 2016
package controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;

public class actionProduct extends ActionSupport {

    private File photo; // Url file được chọn
    private String photoFileName; // Tên file vừa chọn
    private String photoContentType; // Loại file vừa chọn 

    public File getPhoto() {
        return photo;
    }

    public void setPhoto(File photo) {
        this.photo = photo;
    }

    public String getPhotoFileName() {
        return photoFileName;
    }

    public void setPhotoFileName(String photoFileName) {
        this.photoFileName = photoFileName;
    }

    public String getPhotoContentType() {
        return photoContentType;
    }

    public void setPhotoContentType(String photoContentType) {
        this.photoContentType = photoContentType;
    }

    @Override
    public String execute() throws Exception {
        String targetPath = "D:\\project\\images"; // Url đích đến
        File fileToCreate = new File(targetPath, photoFileName);
        try {
            FileUtils.copyFile(this.photo, fileToCreate);
        } catch (IOException e) {
            addActionError(e.getMessage());
        }
        return SUCCESS;
    }

}
Struts.xml
Java 2016
<struts>
    <package name="default" extends="struts-default">

        <action name="insertProduct" class="controller.actionProduct">
            <result name="success">/index.jsp</result>
        </action> 

    </package>
</struts>
Refer http://www.simplecodestuffs.com/struts-2-file-upload-example/

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang