文件上传.

一、文件上传的三种方式

1、上传到tomcat服务器

        自己的电脑:项目在哪里,图片就在哪里

        云服务器:是没有CDEF盘的,只有/跟目录

2、上传到指定文件目录,添加服务器与真实目录的映射关系,从而解耦上传文件与tomcat的关系
      文件服务器和web服务器通常是同一个,但是文件目录与tomcat目录肯定不是同一个

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

     安全性比第二种高

推荐使用的ECS云服务器:阿里云、腾讯云、西部数码云,至少要1核CPU,2G内存的

二、文件上传演示

1、上传文件的界面

        必须是多功能表单(enctype="multipart/form-data" type="file")

<%@ 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 class="form-inline"
        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="img">
        <input type="submit">
    </form>

</body>
</html>

2、struts必须按照指定的格式去接受参数变量

        指定的格式:

                        ①上传的文件

                        ②上传的文件名

                        ③上传的文件类别

 private File img;
    private String imgFileName;
    private String imgContentType;
    public File getImg() {
        return img;
    }

    public void setImg(File img) {
        this.img = img;
    }

    public String getImgFileName() {
        return imgFileName;
    }

    public void setImgFileName(String imgFileName) {
        this.imgFileName = imgFileName;
    }

    public String getImgContentType() {
        return imgContentType;
    }

    public void setImgContentType(String imgContentType) {
        this.imgContentType = imgContentType;
    }

3、web层,写方法

        跳转的方法===>upload.jsp

        上传的方法:

                        将指定的文件图片上传到文件目录

                        将访问图片的请求映射地址更新到数据

//    跳转到文件上传界面
    public String preUpload() throws Exception {
        this.result=this.clzDao.list(clz, null).get(0);
        this.req.setAttribute("result", result);
        return "upload";
    }
    
    public String upload() throws Exception {
//        img代表客户选择的文件或者图片,再将图片上传到其他地方
//        img代表源头,要将其写入目的地target
        String destDir="E:/Temp/mvc/upload";
        String serverDiv="/uploadImages";
//        E:/Temp/mvc/upload/1.png
//        http://localhost:8080/struts/upload/xx.png
        FileUtils.copyFile(img,new File(destDir+"/"+imgFileName));
//        数据库保存的值是/uploadImages/xx.png
//        图片是在E:/Temp/mvc/upload/1.png
//        访问:http://localhost:8080/struts/uploadImages/xx.png
        clz.setPic(serverDiv+"/"+imgFileName);
        this.clzDao.edit(clz);
        return TOLIST;
    }

4、在tomcat中的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="E:/Temp/mvc/upload" path="/uploadImages"/>
      <Context docBase="zw_struts" path="/zw_struts" reloadable="true" source="org.eclipse.jst.jee.server:zw_struts"/></Host>
      
    </Engine>
  </Service>
</Server>

5、配置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="/clz_*" class="com.zw.web.ClzAction" method="{1}" >         
    <result name="list">/clzList.jsp</result>         
    <result name="toEdit">/clzEdit.jsp</result>     
    <result name="toList" type="redirectAction">/clz_list</result> 
    <result name="upload">/upload.jsp</result> 
    </action>    
    </package>
</struts>

6、显示上传的图片(clzList.jsp)

        直接访问img映射地址,通过img标签

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>    
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
<!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">
<link
    href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    rel="stylesheet">
<script
    src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>博客列表</title>
<style type="text/css">
.page-item input {
    padding: 0;
    width: 40px;
    height: 100%;
    text-align: center;
    margin: 0 6px;
}

.page-item input, .page-item b {
    line-height: 38px;
    float: left;
    font-weight: 400;
}

.page-item.go-input {
    margin: 0 10px;
}
</style>
</head>
<body>
    <form class="form-inline"
        action="${pageContext.request.contextPath }/sy/clz_list.action" method="post">
        <div class="form-group mb-2">
            <input type="text" class="form-control-plaintext" name="title"
                placeholder="请输入书籍名称">
<!--             <input name="rows" value="20" type="hidden"> -->
<!-- 不想分页 -->
<!--                 <input name="pagination" value="false" type="hidden"> -->
        </div>
        <button type="submit" class="btn btn-primary mb-2">查询</button>
        <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/sy/clz_toEdit.action">新增</a>
    </form>

    <table class="table table-striped bg-success">
        <thead>
            <tr>
                <th scope="col">ID</th>
                <th scope="col">名字</th>
                <th scope="col">老师</th>
                <th scope="col">操作</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach  var="b" items="${result }">
            <tr>
                <td>${b.cid }</td>
                <td>${b.cname}</td>
                <td>${b.cteacher }</td>
                <td>
                    <img alt="" src="${b.pic }" style="width: 50px;height: 70px;">
                </td>
                <td>
  <a href="${pageContext.request.contextPath }/sy/clz_toEdit.action?cid=${b.cid}">修改</a>
  <a href="${pageContext.request.contextPath }/sy/clz_del.action?cid=${b.cid}">删除</a>
  <a href="${pageContext.request.contextPath }/sy/clz_preUpload.action?   cid=${b.cid}">上传图片</a>
                </td>
            </tr>
            </c:forEach>
        </tbody>
    </table>
    <!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
       <z:page pageBean="${pageBean }"></z:page>  

</body>
</html>

效果展示:

  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值