条件:

1.上传的表单必须以post方式提交

2.提交需要指定编码为multipart/form-data

具体代码如下:

记得要将部分xml文件路径引入到struts.xml中

<include file="/kp10_fileload/fileload.xml"></include>
package kp10_fileload;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUpLoadAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private File image;
    private String imageContentType;// 文件类型
    private String imageFileName;// 文件名

    public void setImage(File image) {
        this.image = image;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String execute() throws Exception {
        System.out.println(image);// 上传的资源路径
        System.out.println(imageFileName);// 获取文件名
        System.out.println(imageContentType);// 文件类型
        String path = ServletActionContext.getServletContext().getRealPath("/FileTransport");// FileTransport文件夹路径
        String fileName = UUID.randomUUID().toString() + "." + imageContentType.split("/")[1];// 整一个UUID作为文件名,将文件类型以"/"分割,保留第一个
        File desFile = new File(path, fileName);// 将路径 和文件名存放进DesFile
        FileUtils.copyFile(image, desFile);// copy文件到该路径

        return SUCCESS;
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>load</title>
</head>
<body>
    <h3>load</h3>
    <hr/>         

<s:form namespace="/fileupload" action="fileup" method="post" enctype="multipart/form-data">(跟xml中的namespace相同)action和xml中的也相同 <s:file name="image"/> <s:submit value="上传"/> </s:form> </body> </html>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="fileupload" namespace="/fileupload" extends="struts-default" >
        <action name="fileup" class="kp10_fileload.FileUpLoadAction" > 
            <result>/JSP/file/file.jsp</result> <!-- 此处路径只是为了让其不报错 -->
        </action>
        
    </package>
    
</struts>

 

posted on 2017-03-11 13:07  小手撬地球  阅读(158)  评论(0编辑  收藏  举报