您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關怎么使用Struts2實現一個文件上傳功能,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
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進行處理
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實現一個文件上傳功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。