struts2文件上传

Posted bf6rc9qu

tags:

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

 

文件上传:
    三种上传方案
    1、上传到tomcat服务器 上传图片的存放位置与tomcat服务器的耦合度太高
    2、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系
    文件服务器

    3、在数据库表中建立二进制字段,将图片存储到数据库

我们使用第二种方案:

package com.huang.crud.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;


import com.huang.crud.dao.ClazzDao;
import com.huang.crud.entity.Clazz;
import com.huang.crud.util.BaseAction;
import com.huang.crud.util.PageBean;
import com.opensymphony.xwork2.ModelDriven;

public class ClazzAction extends BaseAction implements ModelDriven<Clazz> 
    private Clazz clz = new Clazz();
    private ClazzDao clzDao = new ClazzDao();
//    这里的属性名要和表单里的name对应    
    private File file;
//    xxxFileName
    private String fileFileName;
//    xxxContentType
    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 list() 
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        try 
            List<Clazz> list = this.clzDao.list(clz, pageBean);
            request.setAttribute("clzList", list);
            request.setAttribute("pageBean", pageBean);
         catch (InstantiationException | IllegalAccessException | SQLException e) 
            e.printStackTrace();
        
        return "list";
    

    public String preSave() 
        if (clz.getCid() != 0) 
            try 
                this.result = this.clzDao.list(clz, null).get(0);
             catch (InstantiationException | IllegalAccessException | SQLException e) 
                e.printStackTrace();
            
        
        return "preSave";
    

    // preUpload
    /**
     * 跳转上传图片的界面
     * @return
     */
    public String preUpload() 
        try 
            this.result = this.clzDao.list(clz, null).get(0);
         catch (InstantiationException | IllegalAccessException | SQLException e) 
            e.printStackTrace();
        
        return "preUpload";
    
    
    public String upload() 
        String realDir = "E:/img";
        String serverDir = "/upload";
        try 
//            FileUtils.copyFile(file, new File(realDir + "/" +fileFileName));
            copyFile(file, new File(realDir + "/" +fileFileName));
            clz.setPic(serverDir + "/" +fileFileName);
            this.clzDao.edit(clz);
         catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | SQLException e) 
            e.printStackTrace();
        
        return "toList";
    
    
    /**
     * 利用缓冲流技术进行拷贝
     * @param source
     * @param target
     * @throws IOException 
     */
    public void copyFile(File source,File target) throws IOException 
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
        BufferedOutputStream out= new BufferedOutputStream(new FileOutputStream(target));
        byte[] bbuf = new byte[1024];
        int len = 0;
        while((len = in.read(bbuf)) != -1) 
            out.write(bbuf, 0, len);
        
        in.close();
        out.close();
    

    public String add() 
        try 
            this.code = this.clzDao.add(clz);
         catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) 
            e.printStackTrace();
        
        return "toList";
    

    public String del() 
        try 
            this.clzDao.del(clz);
         catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) 
            e.printStackTrace();
        
        return "toList";
    

    public String edit() 
        try 
            this.clzDao.edit(clz);
         catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) 
            e.printStackTrace();
        
        return "toList";
    

    @Override
    public Clazz getModel() 
        return clz;
    

struts_sy.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="sy" extends="base" namespace="/sy">
        <action name="/hello_*" class="com.lyl.web.HelloAction" method="1">
            <result name="success">/success.jsp</result>
        </action>
        
        <action name="/clz_*" class="com.lyl.crud.web.ClazzAction" method="1">
            <result name="list">/clzList.jsp</result>
            <result name="preUpload">/clzUpload.jsp</result>
            <result name="preSave">/clzEdit.jsp</result>
            <result name="toList" type="redirectAction">/clz_list</result>
        </action>
    </package>
</struts>

clzList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="/leiyuanlin" prefix="z" %>
<!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>班级主页面</title>
</head>
<body>
<h2>小说目录</h2>
    <br>

    <form action="$pageContext.request.contextPath/sy/clz_list.action" method="post">
        书名:<input type="text" name="bname"> <input type="submit"
            value="确定">
            <input type="hidden" name="rows" value="3">
    </form>
    <a href="$pageContext.request.contextPath/sy/clz_preSave.action">增加</a>
    <table border="1" width="100%">
        <tr>
            <td>编号</td>
            <td>班级名称</td>
            <td>教员</td>
            <td>班级图片</td>
            <td>操作</td>
        </tr>
        <c:forEach items="$clzList " var="b">
            <tr>
                <td>$b.cid </td>
                <td>$b.cname </td>
                <td>$b.cteacher </td>
                <td>
                <img style="height: 60px;width: 60px" src="$pageContext.request.contextPath$b.pic ">
                </td>
                <td>
                    <a href="$pageContext.request.contextPath/sy/clz_preSave.action?cid=$b.cid">修改</a>&nbsp;
                    <a href="$pageContext.request.contextPath/sy/clz_del.action?cid=$b.cid">删除</a>&nbsp;
                    <a href="$pageContext.request.contextPath/sy/clz_preUpload.action?cid=$b.cid">图片上传</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    <z:page pageBean="$pageBean "></z:page>
</body>
</html>

clzUpload.jsp

<%@ 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>图片上传</title>
</head>
<body>
<form action="$pageContext.request.contextPath/sy/clz_upload.action" method="post" enctype="multipart/form-data">
    <input type="hidden" name="cid" value="$result.cid "><br>
    <input type="hidden" name="cname" value="$result.cname "><br>
    <input type="hidden" name="cteacher" value="$result.cteacher "><br>
    <input type="file" name="file">
    <input type="submit">
</form>
</body>
</html>

找到server.xml  在最后面加入

<Context path="/struts(项目名)/upload" docBase="G:/T226tupian(存储图片的路径)"/>

server.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 --><Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
    -->
    <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
         This connector uses the NIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine defaultHost="localhost" name="Catalina">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
      </Realm>

      <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/>

      <Context docBase="G:/T226" path="/T226_upload" reloadable="true" source="org.eclipse.jst.jee.server:T226_ognl"/>
      <Context docBase="T226_img" path="/T226_img" reloadable="true" source="org.eclipse.jst.jee.server:T226_img"/></Host>
    </Engine>
  </Service>
</Server>

 

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

struts2学习(13)struts2文件上传和下载

struts2文件上传下载

struts2实现文件上传和下载

struts2文件上传

Struts2学习—文件上传和下载

Struts2--文件上传与下载