您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这期内容当中小编将会给大家带来有关怎么使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。