实现struts2的文件上传功能

1 struts2的文件上传

1.1 文件上传准备

1.1.1 页面配置

  • input为file类型
input type="file" name="upload"/>
  • 表单提交方式为post
  • enctypt为multipart/form-data
<FORM id=form1 name=form1
		action="${pageContext.request.contextPath }/customer_save.action"
		method=post enctype="multipart/form-data">

1.1.2 Action的配置

  • 需要有三个重要属性
    • private String uploadFileName // 命名要求:Jsp页面文件上传的name属性值+FileName
    • private File upload; // 命名要求:Jsp页面文件上传的name属性值
    • private String uploadContentType; // 命名要求:Jsp页面文件上传的name属性值+ContentType
  • 并分别为这三个属性添加set方法

1.1.3 代码实现

/**
 * 客户Action
 */
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>
{
    private Customer customer=new Customer();
    
    private CustomerService customerService;
    
    /**
         * 文件名称:jsp页面文件上传的name属性的值+FileName
     */
    private String uploadFileName;
    /**
         * 上传文件:jsp页面文件上传的name属性的值
     */
    private File upload;
    /**
          * 文件类型:jsp页面文件上传的name属性的值+ContentType
     */
    private String uploadContentType;
    
    public void setUploadFileName(String uploadFileName)
    {
        this.uploadFileName = uploadFileName;
    }


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


    public void setUploadContentType(String uploadContentType)
    {
        this.uploadContentType = uploadContentType;
    }

    public void setCustomerService(CustomerService customerService)
    {
        this.customerService = customerService;
    }
    
    public Customer getModel()
    {
        return customer;
    }
    
    /**
         * 添加客户
     * @throws IOException 
     */
    public String save() throws IOException {
        System.out.println(upload);
        if(upload!=null) {
            // 上传后存储的文件路径
            String path="D:\\Java\\WorkSpace\\uploadFile";
            // 由于文件可能非常多,可能导致同名,所以使用uuid作为文件名存储
            String fileName=FileUploadUtils.getUuidFileName(uploadFileName);
            // 由于文件可能过多,如果存储在同一目录下,会导致非常卡顿,所以分开存储
            String dirPath=FileUploadUtils.getFilePath(fileName);
            // 存储文件的目录
            String dir=path+dirPath;
            File fileDir=new File(dir);
            if(!fileDir.exists()) {
                // 目录不存在则创建
                fileDir.mkdirs();
            }
            // 存储文件
            File file=new File(fileDir,fileName);
            // 复制上传文件到存储文件
            FileUtil.copyFile(upload, file);
            // 存储图片路径
            customer.setCust_image(fileDir+"/"+fileName);
        }
        customerService.save(customer);
        return "saveSuccess";
    }
}

1.1.4 文件上传工具类

/**
 * 文件上传工具类
 */
public class FileUploadUtils
{
    /**
     * 获取uuid文件名
     * @Description: getUuidFileName
     */
    public static String getUuidFileName(String uploadFileName) {
        String uuid=uuid();
        if(uploadFileName!=null&& uploadFileName.indexOf(".")!=-1) {
            String suffix=uploadFileName.substring(uploadFileName.lastIndexOf("."));
            uuid=uuid+suffix;
        }
        return uuid;
    }
    
    /**
     * 通过文件名的hashCode获取8层目录结构,共16的8次方的目录,共43亿目录
     * @Description: getFilePath
     */
    public static String getFilePath(String uuidFileName) {
        int hashCode = uuidFileName.hashCode();
        int temp=hashCode;
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<8;i++) {
            sb.append("/").append(temp & 0xf);
            temp=temp>>>1;
        }
        return sb.toString();
    }
    
    /**
     * 获取去处分割线的uuid值
     * @Description: uuid
     */
    public static String uuid() {
        String uuid=UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }
}

1.1.5 设置文件上传大小和格式限制:struts2.xml配置

  • 注意当文件格式或大小不匹配的时候,会出现input错误,所以在action需要配置input
	<!-- 设置上传文件的临时存储路径 -->
	<!-- <constant name="struts.multipart.saveDir" value="d:/upload"/> -->
	<!-- 设置单次上传文件大小为5M -->
	<constant name="struts.multipart.maxSize" value="5242880"/>

	<action name="customer_*" class="customerAction" method="{1}">
			<result name="saveSuccess" type="redirectAction">customer_findAll.action</result>
			<result name="input">/jsp/customer/add.jsp</result>
			
			<interceptor-ref name="defaultStack">
				<!-- 设置单个文件最大大小 -->
				<param name="fileUpload.maximumSize">2097152</param>
				<!-- 设置上传文件类型 -->
				<param name="fileUpload.allowedExtensions">.jpg</param>
			</interceptor-ref>
		</action>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值