Struts2实现上传单个文件功能
程序员文章站
2023-12-19 19:15:58
upload.jsp 这个页面选择提交文件,提交到uploadimage.action
<%@ page language="java" contentty...
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>
成功失败界面随便写一个就行了,不贴了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。