溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用Struts2實現(xiàn)一個文件上傳功能

發(fā)布時間:2020-11-21 16:10:58 來源:億速云 閱讀:128 作者:Leah 欄目:編程語言

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)怎么使用Struts2實現(xiàn)一個文件上傳功能,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

upload.jsp 這個頁面選擇提交文件,提交到uploadImage.action

<%@ 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="uploadImage.action" enctype="multipart/form-data" method="post">
    please select the file:<input type="file" name="upload">
    <input type="submit" value="上傳文件">
  </form>
</body>
</html>

FileUploadAction.java 將傳來的file進(jìn)行處理

package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

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

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport{
  private File upload;
  private String uploadFileName;
  private String uploadContentType;


  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 getUploadContentType() {
    return uploadContentType;
  }


  public void setUploadContentType(String uploadContentType) {
    this.uploadContentType = uploadContentType;
  }


  public String execute(){
    System.out.println(upload);
    System.out.println(uploadContentType);
    System.out.println(uploadFileName);

    String savePath = ServletActionContext.getServletContext().getRealPath("/upload/"+this.uploadFileName);
    System.out.println(savePath);

    try{
      FileInputStream fis = new FileInputStream(upload);
      FileOutputStream fos = new FileOutputStream(savePath);
      IOUtils.copy(fis, fos);
      fos.flush();
      fos.close();
      fis.close();
    }catch(Exception e){
      e.printStackTrace();
    }
    return "success";
  }
}

uploadFileName和uploadContentType,這兩個屬性分別用于封裝上傳文件的文件名、上傳文件的文件類型

Struts.xml配置

<action name="uploadImage" class="action.FileUploadAction">
 <result name="success">uploadSuccess.jsp</result>
 <result name="input">uploadError.jsp</result>
</action>

上述就是小編為大家分享的怎么使用Struts2實現(xiàn)一個文件上傳功能了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI