Struts2文件上传

页面代码:
upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>文件上传</title>
  </head>
  
  <body>
  	<h2>文件上传1</h2>
    <form action="upload/uploadAction" method="post" enctype="multipart/form-data">
    	文件上传: <input type="file" name="file"/><br>
    	<input type="submit" value="上传"/>
    </form>
	<hr>
	<h2>文件上传2</h2>
    <form action="upload2/uploadAction2 method="post" enctype="multipart/form-data">
    	文件上传: <input type="file" name="file"/><br>
    	<input type="submit" value="上传"/>
    </form>
	<hr>
	<s:property value="#msg"/>
	<img alt="图片" src="<%=basePath%>upload/${fileFileName}">
  </body>
</html>


struts.xml配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
	<constant name="struts.devMode" value="true"></constant>
	<!--解决乱码    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
	
	<package name="upload" namespace="/upload" extends="struts-default"> 
		<global-results>
    		<result name="error">/error.jsp</result>
    	</global-results>
    	
    	<global-exception-mappings>
    		<exception-mapping result="error" exception="IOException"></exception-mapping>
    	</global-exception-mappings>
    	
    	<action name="uploadAction" class="com.edifier.action.UploadAction" method="upload">
    		<result name="success">/upload.jsp</result>
    	</action>    	
	</package>
	
	<package name="upload2" namespace="/upload2" extends="struts-default">
    	<action name="uploadAction2" class="com.edifier.action.UploadAction2" method="upload2">
    		<param name="savePath">/upload</param>
    		<result name="success">/upload.jsp</result>
    		<result name="input">/error.jsp</result>
    		<interceptor-ref name="fileUpload">
                <!-- 文件过滤 -->
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
                <!-- 文件大小, 以字节为单位,如果没有配置常量struts.multipart.maxSize,
					那么下面这个配置有效,否则文件大小看常量配置的大小 -->
                <param name="maximumSize">10701096</param>
            </interceptor-ref>
            <!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
            <interceptor-ref name="defaultStack" />
    	</action>
	</package>	
</struts>

Action类写法一:
package com.edifier.action;

import java.io.File;
import java.io.IOException;

import org.apache.struts2.ServletActionContext;
import org.aspectj.util.FileUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport{
	
	private File file;				//文件路径
	private String fileFileName;	//文件名
	private String fileContentType; //文件类型
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
	public String upload() throws IOException{
		String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
		System.out.println("RealPath: " + realPath);//此为上传目录地址
		
		if(null != file){
			//根据 realPath 抽象路径名和 child 路径名字符串创建一个新 File 实例。
			File saveFile = new File(new File(realPath), fileFileName);
			if(!saveFile.getParentFile().exists()){
				saveFile.getParentFile().mkdir();//如果上传目录不存在,创建该目录
			}
			FileUtil.copyFile(file, saveFile);//调用java.io.FileUtil类中的copyFile方法,复制文件
			ActionContext.getContext().put("msg", "上传成功");//向值栈中存放一个msg的参数
		}
		return SUCCESS;
	}
}

Action类写法二:
package com.edifier.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction2 extends ActionSupport{

	private File file;
	private String fileFileName;
	private String fileContentType;
	private String savePath;//将上传目录名配置在struts.xml中,通过依赖注入获得目录名
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath); //获取上传目录绝对路径
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	public String upload2() throws IOException{
		String saveFilePath = getSaveFile() + "/" + getFileFileName();//文件保存的绝对路径
		
		copyFile(saveFilePath,file);
		
		return SUCCESS;
	}
	//自定义复制文件方法,最好放在工具类中,saveFilePath上传目录路径,file上传的文件
	private void copyFile(String saveFilePath, File file){
		FileOutputStream fos = null;
        FileInputStream fis = null;
        try{
        	// 建立文件输出流
        	System.out.println(saveFilePath);
        	fos = new FileOutputStream(saveFilePath);
        	// 建立文件上传流
        	fis = new FileInputStream(file);
        	byte[] buffer = new byte[1024];
        	int len = 0;
        	while ((len = fis.read(buffer)) > 0) {
        		fos.write(buffer, 0, len);
        	}
        } catch (Exception e) {
        	System.out.println("文件上传失败");
        	e.printStackTrace();
        } finally {
        	close(fos, fis);
        }
	}
	private void close(FileOutputStream fos, FileInputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                System.out.println("FileInputStream关闭失败");
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                System.out.println("FileOutputStream关闭失败");
                e.printStackTrace();
            }
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值