Struts2之上传下载

Posted 姜文文

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Struts2之上传下载相关的知识,希望对你有一定的参考价值。

单文件上传

上传页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<form action="upload.action" method="post" enctype="multipart/form-data">
    文件:<input type="file" name="upload"><br><br>
    上传者:<input type="text" name="author">
    <input type="submit" value="上传">
</form>
</body>
</html>

struts.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="jiangwenwen" namespace="/" extends="struts-default">
    <action name="upload" class="cn.jiangwenwen.action.UploadAction" method="fileUpload">
        <result name="success">/success.jsp</result>
    </action>
</package>
</struts>

Action类

public class UploadAction  extends ActionSupport{
    
    //存放上传的文件对象
    private File upload;    
    //上传的文件名称
    private String uploadFileName;
    //上传的上传者
    private String author;
    
    public String fileUpload() throws IOException {
        
        FileInputStream fis = new FileInputStream(upload);
        
        String path = "D://pic/"+uploadFileName;
        
        FileOutputStream fos = new FileOutputStream(path);
        
        int flag = 0;
        
        while((flag=fis.read())!=-1) {
            fos.write(flag);
        }
        fis.close();
        fos.close();
        
        return SUCCESS;
        
    }

    public File getUpload() {
        return upload;
    }

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

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
    
}

成功接收页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<!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>Insert title here</title>
</head>
<body>
<!-- 此 /pic为服务器配置的路径-->
<img src="/pic/${uploadFileName }">
</body>
</html>

以上是关于Struts2之上传下载的主要内容,如果未能解决你的问题,请参考以下文章

Struts2之HelloWorld

struts2学习笔记之十:文件上传

Struts2之上传下载

Struts2之文件上传下载

Struts2之上传文件

java之struts2之文件下载