struts2文件上传与下载

一、场景

完成个人注册图片的上传,并在注册成功后,可以下载自己注册时上传的图片

二、实现

上传action

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.io.*;
import java.util.UUID;

public class FileAction extends ActionSupport {

    private User user;
    private File myUpload;//文件
    private String myUploadFileName;//文件名
    private String myUploadContentType;//文档类型
    private String savePath;//存储路径

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public File getMyUpload() {
        return myUpload;
    }

    public void setMyUpload(File myUpload) {
        this.myUpload = myUpload;
    }


    public String getMyUploadFileName() {
        return myUploadFileName;
    }

    public void setMyUploadFileName(String myUploadFileName) {
        this.myUploadFileName = myUploadFileName;
    }

    public String getMyUploadContentType() {
        return myUploadContentType;
    }

    public void setMyUploadContentType(String myUploadContentType) {
        this.myUploadContentType = myUploadContentType;
    }

    //返回文件上传的保存位置
    public String getSavePath() {
        String str = ServletActionContext.getServletContext().getRealPath(savePath);
        return str;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public String upload() throws IOException {
        String newName = UUID.randomUUID().toString();//新的方法名
        String sufix = myUploadFileName.substring(myUploadFileName.lastIndexOf("."));//获取后缀名
        newName+=sufix;//新文件名
        //以服务器的文件保存地址和原文件名建立上传文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(getSavePath()+"\\"+newName);
        System.out.println(getSavePath());
        myUploadFileName = newName;
        FileInputStream fileInputStream = new FileInputStream(getMyUpload());
        System.out.println(fileOutputStream);
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(bytes))>0){
            fileOutputStream.write(bytes,0,len);
        }
        fileOutputStream.close();
        return SUCCESS;
    }
}

下载action

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.io.FileNotFoundException;
import java.io.InputStream;

public class FileDowm extends ActionSupport {

    private String name;
    private String contentType;

    public String getContentType() {
        return ServletActionContext.getServletContext().getMimeType(name);
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public InputStream getFile1() throws FileNotFoundException {
        return ServletActionContext.getServletContext().getResourceAsStream("/"+name);
    }

    @Override
    public String execute() throws Exception {
        System.out.println(name);
        return SUCCESS;
    }
}

struts2.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>
    <package name="user7" extends="struts-default">
        <action name="uplode" class="seven.FileAction" method="upload">
            <param name="savePath">/</param>
            <result name="success">/7/filedownload.jsp</result>
        </action>
        <action name="down" class="seven.FileDowm" method="execute">
            <result name="success" type="stream">
                <param name="contentType">application/octet-stream;charset=ISO8859-1</param>
                <param name="contentDisposition">attachment;filename="${name}"</param>
                <param name="inputName">file1</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>
    </package>
</struts>

上传页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
<form action="uplode.action" method="post" enctype="multipart/form-data">
    <h2>上传</h2>
    用户名:<input type="text" name="user.name"/>
    密码:<input type="password" name="user.pass"/>
    上传:<<input type="file" name="myUpload">
    <input type="submit" value="提交" />
</form>
</body>
</html>

下载页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>上传成功</title>
</head>
<body>
    <s:property value="myUploadFileName" />
    上传成功:<a href="down.action?name=<s:property value="myUploadFileName"/>">下载</a><br>
    <img src="<s:property value="'/'+myUploadFileName" />">
</body>
</html>

三、问题与解决

①struts2.xml文件引入失败

<include file="five/fivestruts.xml"></include>
<include file="six/sixstruts.xml"></include>
<include file="seven/sevenstruts2.xml"></include>

解决:在设置model处添加(删除后统一添加所有xml


getRealPath报红线,方法找不到

ServletActionContext.getServletContext().getRealPath(savePath)

解决tomcat下找到servlet-api jar包引入到项目中;


③动态下载上传的内容xml配置

<result name="success" type="stream">
    <param name="contentType">application/octet-stream;charset=ISO8859-1</param>
    <param name="contentDisposition">attachment;filename="${name}"</param>
    <param name="inputName">file1</param>
    <param name="bufferSize">4096</param>
</result>

解决:使用ognl表达式动态化,需要action提供get方法!

如:file1

public InputStream getFile1() throws FileNotFoundException {
    return ServletActionContext.getServletContext().getResourceAsStream("/"+name);
}


④超链接传参参数不正确

解决:name=xx  不加引号!,简单的问题困扰好久

<a href="down.action?name=<s:property value="myUploadFileName"/>" />


⑤idea在上传文件时建立文件夹发现tomacat/webapp下并没有自己部署的项目

解决:这是因为idea项目并没有部署到wenapp下,而是有自己的虚拟目录

 


猜你喜欢

转载自blog.csdn.net/menglinjie/article/details/80299399
今日推荐