一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - struts2單個文件上傳的兩種實現方式

struts2單個文件上傳的兩種實現方式

2019-10-27 12:25java技術網 JAVA教程

這篇文章主要介紹了struts2單個文件上傳的兩種實現方式,有需要的朋友可以參考一下

通過2種方式模擬單個文件上傳,效果如下所示

struts2單個文件上傳的兩種實現方式

開發步驟如下:

1、新建一個web工程,導入struts2上傳文件所需jar,如下圖

struts2單個文件上傳的兩種實現方式

目錄結構

struts2單個文件上傳的兩種實現方式

2、新建Action

第一種方式

 

復制代碼代碼如下:


package com.ljq.action;

 

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

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

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{

    private File image; //上傳的文件
    private String imageFileName; //文件名稱
    private String imageContentType; //文件類型

    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        //D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
        System.out.println("realpath: "+realpath);
        if (image != null) {
            File savefile = new File(new File(realpath), imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(image, savefile);
            ActionContext.getContext().put("message", "文件上傳成功");
        }
        return "success";
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    
}

 

第二種方式

 

復制代碼代碼如下:


package com.ljq.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;

@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport {

    // 封裝上傳文件域的屬性
    private File image;
    // 封裝上傳文件類型的屬性
    private String imageContentType;
    // 封裝上傳文件名的屬性
    private String imageFileName;
    // 接受依賴注入的屬性
    private String savePath;

    @Override
    public String execute() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            // 建立文件輸出流
            System.out.println(getSavePath());
            fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName());
            // 建立文件上傳流
            fis = new FileInputStream(getImage());
            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);
        }
        return SUCCESS;
    }

    /**
     * 返回上傳文件的保存位置
     * 
     * @return
     */
    public String getSavePath() throws Exception{
        return ServletActionContext.getServletContext().getRealPath(savePath); 
    }

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

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    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();
            }
        }
    }

}

 

struts.xml配置文件

 

復制代碼代碼如下:


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

 

<struts>
    <!-- 該屬性指定需要Struts2處理的請求后綴,該屬性的默認值是action,即所有匹配*.action的請求都由Struts2處理。
        如果用戶需要指定多個請求后綴,則多個后綴之間以英文逗號(,)隔開。 -->
    <constant name="struts.action.extension" value="do" />
    <!-- 設置瀏覽器是否緩存靜態內容,默認值為true(生產環境下使用),開發階段最好關閉 -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!-- 當struts的配置文件修改后,系統是否自動重新加載該文件,默認值為false(生產環境下使用),開發階段最好打開 -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 開發模式下使用,這樣可以打印出更詳細的錯誤信息 -->
    <constant name="struts.devMode" value="true" />
    <!-- 默認的視圖主題 -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!--解決亂碼    -->
    <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">
        <action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>

    <package name="upload2" extends="struts-default">
        <action name="upload2" class="com.ljq.action.UploadAction2" method="execute">
            <!-- 動態設置savePath的屬性值 -->
            <param name="savePath">/images</param>
            <result name="success">/WEB-INF/page/message.jsp</result>
            <result name="input">/upload/upload.jsp</result>
            <interceptor-ref name="fileUpload">
                <!-- 文件過濾 -->
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
                <!-- 文件大小, 以字節為單位 -->
                <param name="maximumSize">1025956</param>
            </interceptor-ref>
            <!-- 默認攔截器必須放在fileUpload之后,否則無效 -->
            <interceptor-ref name="defaultStack" />
        </action>
    </package>
</struts>

 

上傳表單頁面

 

復制代碼代碼如下:


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>文件上傳</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
    </head>

    <body>
        <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
        <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
        <form action="${pageContext.request.contextPath}/upload2/upload2.do" 
              enctype="multipart/form-data" method="post">
            文件:<input type="file" name="image">
                <input type="submit" value="上傳" />
        </form>
        <br/>
        <s:fielderror />
    </body>
</html>

 

顯示結果頁面

 

復制代碼代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>上傳成功</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
  </head>

  <body>
    上傳成功!
    <br/><br/>
    <!-- ${pageContext.request.contextPath} tomcat部署路徑,
          如:D:\apache-tomcat-6.0.18\webapps\struts2_upload\ -->
    <img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">
    <s:debug></s:debug>
  </body>
</html>
 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日韩大片在线 | 高清国产激情视频在线观看 | 太深了 太粗h1v1 | 久久五月综合婷婷中文云霸高清 | 久久精品一区二区三区资源网 | 日韩夫妻性生活 | 精品亚洲综合久久中文字幕 | 日本一道一区二区免费看 | 久久国产精品永久免费网站 | 欧洲喷浆乌克兰 | 欧美性videossex丝袜 | 精品国产人妻国语 | 亚洲AV福利天堂一区二区三 | www.久久av.com| 亚洲精品高清中文字幕完整版 | 亚洲精品日韩专区在线观看 | 无遮挡免费h肉动漫在线观看 | 操美女| 欧美大片一级片 | 成人免费国产欧美日韩你懂的 | 美女大乳被捏羞羞漫画 | 男同互操| 香蕉人人超人人超碰超国产 | 亚洲AV无码乱码国产麻豆穿越 | 国产一区二区播放 | 午夜爱 | 欧产日产国产精品专区 | 免费一级黄 | 午夜一区二区三区 | pron欧美| ass亚洲熟妇毛茸茸pics | 手机在线观看精品国产片 | 视频一区二区在线 | 久久精品国产免费 | 公交车上插入 | 秋霞午夜 | 国产伦精品一区二区三区女 | 极品主播的慰在线播放 | 美女裆部| 动漫精品一区二区三区3d | 国产精品每日在线观看男人的天堂 |