struts2上传文件

fileupload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
  </head> 
  <body>

    <h1>Action文件上传</h1>
    <s:form method="post" enctype="multipart/form-data" action="up">
      <s:file label="上传文件" name="file" />
      <s:submit></s:submit>
    </s:form>
  </body>
</html>

 struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">
         
<struts>
<!-- 为了使用struts2提供的功能,需要继承系统提供的包default -->
	<package name="struts2" extends="struts-default">
		 		<!-- 文件上传 -->
		<action name="up" class="com.fileupload.UploadAction">
			<interceptor-ref name="execAndWait"/>
			<result name="wait">/wait.jsp</result>
			<result >/ok.jsp</result>
		</action>   
	</package>
</struts>

 struts.properties

struts.devMode=false
struts.ognl.allowStaticMethodAccess=true
struts.multipart.saveDir=d:/
struts.multipart.maxSize=4097152

 

UploadAction.java

package com.fileupload;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;

public class UploadAction implements Action {
	private File file;
	private String contentType;
	private String fileName;

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setFileFileName(String fileName) {
		this.fileName = fileName;
	}

	public String execute() {
		String path = ServletActionContext.getServletContext().getRealPath("");
		
		try {
			FileInputStream fis = new FileInputStream(file);
			FileOutputStream fos = new FileOutputStream(path+"/"+fileName);
			byte[] bytes = new byte[1024];
			int num = 0;
			while((num = fis.read(bytes))>0){
				fos.write(bytes,0,num);
			}
			fos.flush();
			fos.close();
			fis.close();
			
			System.out.println("ok");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
}

File 

ContentType

FileName

这三个属性是必须的,在写set方法时必须是:

setFile   setFileContentType   setFileFileName

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值