分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

Struts文件上传(FormFile)

发布时间:2023-09-06 01:06责任编辑:蔡小小关键词:文件上传

Struts中FormFile用于文件进行上传

1.在jsp文件中进行定义

<form action="/StrutsFileUpAndDown/register.do" method="post" enctype="multipart/form-data"> ??名字:<input type="text" name="name" /> ??头像:<input type="file" name="file"/> ??<input type="submit" value="注册用户"> ??</form>

2.在Form表单中定义FormFile

/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */package com.yourcompany.struts.form;import javax.servlet.http.HttpServletRequest;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;/** ?* MyEclipse Struts * Creation date: 08-24-2017 * ?* XDoclet definition: * @struts.form name="userForm" */public class UserForm extends ActionForm {/* * Generated Methods */private String username;private FormFile file;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public FormFile getFile() {return file;}public void setFile(FormFile file) {this.file = file;}}

  

3.利用struts文件进行关联Form,关联以后

1)利用表单实例进行获取FormFile实例,在获取以后,我们可以通过FormFile获取上传文件的各种信息

UserForm userForm = (UserForm) form;String username = userForm.getUsername();FormFile file = userForm.getFile();//通过formFile可以获取关于用户上传文件的各种信息//用于获取文件名字String fileName = file.getFileName();//用于获取文件大小int fileSize = file.getFileSize();

  

2)通过FormFile实例获取输入流,创建一个输出流,并且在代码中获取tomcat服务器的绝对路径

try {//获取输入流is = file.getInputStream();//得到输出流//1.得到file文件夹,上传到tomcat服务器后的绝对路径(file文件为新创建的文件夹) String filePath = this.getServlet().getServletContext().getRealPath("/file");//两个"//"的其中一个"/"为转义符 os=new FileOutputStream(filePath+"\\"+fileName); int len=0;//表示读取的字节//做一个缓存,防止文件过大而造成错误byte[] buff=new byte[1024];while((len=is.read(buff))!=-1){os.write(buff,0,len);}is.close();os.close(); }

  

Struts文件上传(FormFile)

原文地址:http://www.cnblogs.com/callyblog/p/7425138.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved