Struts的FormFile做上传处理,怎样去控制上传文件的后缀名和类型 (比如 只能让上传.jpg的文件 其他的文件在对话框里面就不显示出来 ,这样就不用在服务器去做类型判断了) 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 在做开发时难免会碰到上传文件,近来我就来和大家分享一下心得,供大家讨论.多提宝贵意见.在struts中上传文件当然要用struts的标签了,<html:file>.用该标签是需要注意以下几点:<html:file> 该标签必须和,<html:form>一起使用并且必须嵌套在<html:form>中,其实struts的html标签必须要写在<html:form>中. <html:form>中的method属性必须是post. <html:form>的enctype属性必须是multipart/form-data <html:file>必须设置property属性,并且该属性的值必须和ActionFormBean 中的 org.apache.struts.upload.FormFile类型属性对应. upload.jsp代码如下: <%...@ page language="java" pageEncoding="utf-8"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-template" prefix="template"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-nested" prefix="nested"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html:html locale="true"><head> <html:base /> <title>upload.jsp</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --></head><body> <h3> 上传文件测试 </h3> <html:form action="upload.do" method="post" enctype="multipart/form-data"> <html:file property="file"></html:file><br> <html:submit></html:submit> </html:form></body></html:html>(upload.jsp) 大家注意upload.jsp中<html:file> 的property属性.该值和actionfrom的属性相同,HtmlfileForm代码如下/**//* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */package com.uploadtest.struts.form;import javax.servlet.http.HttpServletRequest;import org.apache.struts.action.ActionErrors;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.upload.FormFile;/** *//** * MyEclipse Struts Creation date: 02-29-2008 * * XDoclet definition: * * @struts.form name="htmlfileForm" */public class HtmlfileForm extends ActionForm ...{ /**//* * Generated Methods */ private FormFile file; public FormFile getFile() ...{ return file; } public void setFile(FormFile file) ...{ this.file = file; } /** *//** * Method validate * * @param mapping * @param request * @return ActionErrors */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) ...{ // TODO Auto-generated method stub return null; } /** *//** * Method reset * * @param mapping * @param request */ public void reset(ActionMapping mapping, HttpServletRequest request) ...{ // TODO Auto-generated method stub }}(HtmlfileForm)然后就是最主要的处理代码部分代码如下(UploadAction),在该Action中做了很多处理,都有注释,自己看./**//* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */package com.uploadtest.struts.action;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.action.ActionMessage;import org.apache.struts.upload.FormFile;import com.uploadtest.struts.form.HtmlfileForm;/** *//** * MyEclipse Struts Creation date: 02-29-2008 * * XDoclet definition: * * @struts.action path="/upload" name="htmlfileForm" input="/upload.jsp" * scope="request" validate="true" */public class UploadAction extends Action ...{ /**//* * Generated Methods */ /** *//** * Method execute * * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) ...{ // webapps/uploadtest/upload String dir = servlet.getServletContext().getRealPath("/upload"); List<String> list = new ArrayList<String>();//注意文件类型最好全部用小写 list.add("jpg"); list.add("jpeg"); list.add("gif"); list.add("bmp"); // 允许上传的文件类型列表可以写在配置文件中,通过xml的解析获得。 if (!dir.endsWith("/")) dir = dir.concat("/"); HtmlfileForm htmlfileForm = (HtmlfileForm) form;// TODO Auto-generated // method stub FormFile file = htmlfileForm.getFile(); if (file == null) ...{ return mapping.getInputForward(); } String fname = file.getFileName();// 获取文件名 int fsize = file.getFileSize();// 获取文件大小 String ext = fname.substring(fname.lastIndexOf(".") + 1, fname.length()); // 获取文件类型,即扩展名,通过String类的substring方法截取字符串,lastIndexOf获取某个字符串最后出现的索引。 ext = ext.toLowerCase();// 全部转换成小写。 if (!list.contains(ext)) ...{// 判断该类型是否为允许上传的文件类型 System.out.println("不支持该文件类型上传,该文件类型是:" + ext); // 可以在此构建ActionMessage对象并返回页面显示错误 return mapping.getInputForward(); } if (fsize > 1024 * 1024) ...{// 判断文件大小是否为允许上传的大小。 // 可以在此构建ActionMessage对象并返回页面显示错误 System.out.println("文件太大"); return mapping.getInputForward(); } InputStream in = null;// 输入流用来读取用户上传文件 OutputStream out = null;// 用来将用户上传文件存出在服务器特定目录中。 try ...{ in = file.getInputStream(); out = new FileOutputStream(dir + fname); int byteread = 0; byte[] bytes = new byte[8192]; while ((byteread = in.read(bytes, 0, 8192)) != -1) ...{ out.write(bytes, 0, byteread); } } catch (Exception e) ...{ System.out.println(e.getMessage()); return mapping.getInputForward(); } finally ...{ try ...{ in.close(); out.close(); } catch (Exception e) ...{ System.out.println(e.getMessage()); return mapping.getInputForward(); } } System.out.println("chenggong"); return mapping.findForward("suc");//suc只是一个成功跳转的设置. }}(UploadAction)以下是struts的配置文件.<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <data-sources /> <form-beans> <form-bean name="htmlfileForm" type="com.uploadtest.struts.form.HtmlfileForm" /> </form-beans> <global-exceptions /> <global-forwards /> <action-mappings> <action attribute="htmlfileForm" input="/upload.jsp" name="htmlfileForm" path="/upload" scope="request" type="com.uploadtest.struts.action.UploadAction"> <forward name="suc" path="/suc.jsp" /> </action> </action-mappings> <controller processorClass="com.uploadtest.struts.util.CharSet"></controller> <message-resources parameter="com.uploadtest.struts.ApplicationResources" /></struts-config>以上是个人的一点愚见,如有不对,请指正. 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/bt_lose/archive/2008/02/29/2134952.aspx 楼上的你好!也许你没看清我问题的题意,我的意思是 直接在弹出那个选择文件的对话框的时候,就不显示那些 不是图片文件 以外的任何文件 , 这样 我就不需要在Action里面去判断选择的文件的类型了 想在客户端处理可以通过js来控制提交的表单,如在form的onsubmit写个函数,检查文件名尾lastindexof <script> function check(v){ var ar=v.split("."); if(/gif|GIF|jpg|JPG|bmp|BMP/.test(ar[ar.length-1])){ document.all.aaaa.src=v; } else{ document.all.aaaa.src=''; alert('您选择的文件扩展名为 '+ar[ar.length-1]+'\n\n 不合要求,请重新选择!') } } </script>上传文件:<input type="file" name="aaaa" onChange="check(this.value)"> 自定义tag就好了让文件类型为*.jpg 首先按你说的必须在客户端判断,不在服务器肯定用JS,这样解决吧,不是有个input tpye="file"这个吗JS应该放在这个上面,是吧。写个function来判断下,你试试 <form id="uploadForm" name="uploadForm" method="post" enctype="multipart/form-data"><input type="file" id="myFile" name="myFile"><input type="button" value="检测是否是图片格式" onclick="isImages()"></form><script>function isImages(){ var regImg = new RegExp(/\.(gif|GIF|jpg|JPG|jpeg|JPEG)$/); var obj=document.getElementById('myFile').value; if(obj.match(regImg)){ alert('是正确的图片格式'); }else{ alert('请上传图片格式文件'); }}</script> smtp发送邮件的问题 自己想的问题,想跟大家一起讨论一下. struts2 又出问题 hibernate中一对一主键关联映射怎样级联删除 我这个图片另存为怎么做? html转JPG 请问诸位高手:在JAVA中如何根据某个域名得到这个域名的IP地址? java使用processbuilder来调用本地杀毒软件对指定文件扫描无效 请教各位一个问题:我的这段代码为什么很慢,而且执行不出来 JSP中可以写函数吗? spring+jdbc事务控制问题 请教 hibernate 多对一的问题
<html:form>中的method属性必须是post.
<html:form>的enctype属性必须是multipart/form-data
<html:file>必须设置property属性,并且该属性的值必须和ActionFormBean 中的 org.apache.struts.upload.FormFile类型属性对应.
upload.jsp代码如下: <%...@ page language="java" pageEncoding="utf-8"%><%...@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
prefix="bean"%>
<%...@ taglib uri="http://jakarta.apache.org/struts/tags-html"
prefix="html"%>
<%...@ taglib uri="http://jakarta.apache.org/struts/tags-logic"
prefix="logic"%>
<%...@ taglib uri="http://jakarta.apache.org/struts/tags-tiles"
prefix="tiles"%>
<%...@ taglib uri="http://jakarta.apache.org/struts/tags-template"
prefix="template"%>
<%...@ taglib uri="http://jakarta.apache.org/struts/tags-nested"
prefix="nested"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html locale="true">
<head>
<html:base /> <title>upload.jsp</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--></head><body>
<h3>
上传文件测试
</h3>
<html:form action="upload.do" method="post" enctype="multipart/form-data">
<html:file property="file"></html:file><br>
<html:submit></html:submit>
</html:form>
</body>
</html:html>(upload.jsp) 大家注意upload.jsp中<html:file> 的property属性.该值和actionfrom的属性相同,HtmlfileForm代码如下/**//*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.uploadtest.struts.form;import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;/** *//**
* MyEclipse Struts Creation date: 02-29-2008
*
* XDoclet definition:
*
* @struts.form name="htmlfileForm"
*/
public class HtmlfileForm extends ActionForm ...{
/**//*
* Generated Methods
*/ private FormFile file; public FormFile getFile() ...{
return file;
} public void setFile(FormFile file) ...{
this.file = file;
} /** *//**
* Method validate
*
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) ...{
// TODO Auto-generated method stub
return null;
} /** *//**
* Method reset
*
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) ...{
// TODO Auto-generated method stub
}
}
(HtmlfileForm)然后就是最主要的处理代码部分代码如下(UploadAction),在该Action中做了很多处理,都有注释,自己看./**//*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.uploadtest.struts.action;import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;import com.uploadtest.struts.form.HtmlfileForm;/** *//**
* MyEclipse Struts Creation date: 02-29-2008
*
* XDoclet definition:
*
* @struts.action path="/upload" name="htmlfileForm" input="/upload.jsp"
* scope="request" validate="true"
*/
public class UploadAction extends Action ...{
/**//*
* Generated Methods
*/ /** *//**
* Method execute
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) ...{
// webapps/uploadtest/upload
String dir = servlet.getServletContext().getRealPath("/upload");
List<String> list = new ArrayList<String>();//注意文件类型最好全部用小写
list.add("jpg");
list.add("jpeg");
list.add("gif");
list.add("bmp");
// 允许上传的文件类型列表可以写在配置文件中,通过xml的解析获得。 if (!dir.endsWith("/"))
dir = dir.concat("/");
HtmlfileForm htmlfileForm = (HtmlfileForm) form;// TODO Auto-generated
// method stub
FormFile file = htmlfileForm.getFile();
if (file == null) ...{
return mapping.getInputForward();
}
String fname = file.getFileName();// 获取文件名
int fsize = file.getFileSize();// 获取文件大小
String ext = fname.substring(fname.lastIndexOf(".") + 1, fname.length());
// 获取文件类型,即扩展名,通过String类的substring方法截取字符串,lastIndexOf获取某个字符串最后出现的索引。
ext = ext.toLowerCase();// 全部转换成小写。
if (!list.contains(ext)) ...{// 判断该类型是否为允许上传的文件类型
System.out.println("不支持该文件类型上传,该文件类型是:" + ext);
// 可以在此构建ActionMessage对象并返回页面显示错误
return mapping.getInputForward();
}
if (fsize > 1024 * 1024) ...{// 判断文件大小是否为允许上传的大小。
// 可以在此构建ActionMessage对象并返回页面显示错误
System.out.println("文件太大");
return mapping.getInputForward();
} InputStream in = null;// 输入流用来读取用户上传文件
OutputStream out = null;// 用来将用户上传文件存出在服务器特定目录中。
try ...{
in = file.getInputStream();
out = new FileOutputStream(dir + fname);
int byteread = 0;
byte[] bytes = new byte[8192];
while ((byteread = in.read(bytes, 0, 8192)) != -1) ...{
out.write(bytes, 0, byteread);
}
} catch (Exception e) ...{
System.out.println(e.getMessage());
return mapping.getInputForward();
} finally ...{
try ...{
in.close();
out.close();
} catch (Exception e) ...{
System.out.println(e.getMessage());
return mapping.getInputForward();
}
}
System.out.println("chenggong");
return mapping.findForward("suc");//suc只是一个成功跳转的设置.
}
}
(UploadAction)以下是struts的配置文件.<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config>
<data-sources />
<form-beans>
<form-bean name="htmlfileForm"
type="com.uploadtest.struts.form.HtmlfileForm" />
</form-beans> <global-exceptions />
<global-forwards />
<action-mappings>
<action attribute="htmlfileForm" input="/upload.jsp"
name="htmlfileForm" path="/upload" scope="request"
type="com.uploadtest.struts.action.UploadAction">
<forward name="suc" path="/suc.jsp" />
</action>
</action-mappings>
<controller processorClass="com.uploadtest.struts.util.CharSet"></controller>
<message-resources
parameter="com.uploadtest.struts.ApplicationResources" /></struts-config>以上是个人的一点愚见,如有不对,请指正. 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/bt_lose/archive/2008/02/29/2134952.aspx
直接在弹出那个选择文件的对话框的时候,就不显示那些
不是图片文件 以外的任何文件 ,
这样 我就不需要在Action里面去判断选择的文件的类型了
<script>
function check(v){
var ar=v.split(".");
if(/gif|GIF|jpg|JPG|bmp|BMP/.test(ar[ar.length-1])){
document.all.aaaa.src=v;
}
else{
document.all.aaaa.src='';
alert('您选择的文件扩展名为 '+ar[ar.length-1]+'\n\n 不合要求,请重新选择!')
}
}
</script>
上传文件:<input type="file" name="aaaa" onChange="check(this.value)">
让文件类型为*.jpg
肯定用JS,这样解决吧,不是有个input tpye="file"这个吗
JS应该放在这个上面,是吧。
写个function来判断下,你试试
<form id="uploadForm" name="uploadForm" method="post" enctype="multipart/form-data">
<input type="file" id="myFile" name="myFile">
<input type="button" value="检测是否是图片格式" onclick="isImages()"></form><script>
function isImages(){
var regImg = new RegExp(/\.(gif|GIF|jpg|JPG|jpeg|JPEG)$/);
var obj=document.getElementById('myFile').value;
if(obj.match(regImg)){
alert('是正确的图片格式');
}else{
alert('请上传图片格式文件');
}
}
</script>