Ⅰ 得到file的文件名和存储路径后,在Struts2中的action中要怎样获取file的内容并显示到action转到的jsp页面中
struts2单文件上传:
首先是一个文件上传页面,这个比较简单,就是一个表单,里面有个文件上传框
<!--在进行文件上传时,表单提交方式一定要是post的方式,因为文件上传时二进制文件可能会很大,还有就是enctype属性,这个属性一定要写成multipart/form-data,
不然就会以二进制文本上传到服务器端-->
<form action="fileUpload.action" method="post" enctype="multipart/form-data">
username: <input type="text" name="username"><br>
file: <input type="file" name="file"><br>
<input type="submit" value="submit">
</form>
接下来是FileUploadAction部分代码,因为struts2对上传和下载都提供了很好的实习机制,所以在action这段我们只需要写很少的代码就行:
public class FileUploadAction extends ActionSupport
{
private String username;
//注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
private File file;
//提交过来的file的名字
private String fileFileName;
//提交过来的file的MIME类型
private String fileContentType;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public File getFile()
{
return file;
}
public void setFile(File file)
{
this.file = file;
}
public String getFileFileName()
{
return fileFileName;
}
public void setFileFileName(String fileFileName)
{
this.fileFileName = fileFileName;
}
public String getFileContentType()
{
return fileContentType;
}
public void setFileContentType(String fileContentType)
{
this.fileContentType = fileContentType;
}
@Override
public String execute() throws Exception
{
String root = ServletActionContext.getServletContext().getRealPath("/upload");
InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(new File(root, fileFileName));
System.out.println("fileFileName: " + fileFileName);
// 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
System.out.println("file: " + file.getName());
System.out.println("file: " + file.getPath());
byte[] buffer = new byte[500];
int length = 0;
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
os.close();
is.close();
return SUCCESS;
}
}
首先我们要清楚一点,这里的file并不是真正指代jsp上传过来的文件,当文件上传过来时,struts2首先会寻找struts.multipart.saveDir(这个是在default.properties里面有)这个name所指定的存放位置,我们可以新建一个struts.properties属性文件来指定这个临时文件存放位置,如果没有指定,那么文件会存放在tomcat的apache-tomcat-7.0.29\work\Catalina\localhost\目录下,然后我们可以指定文件上传后的存放位置,通过输出流将其写到流里面就行了,这时我们就可以在文件夹里看到我们上传的文件了。
文件上传后我们还需要将其下载下来,其实struts2的文件下载原理很简单,就是定义一个输入流,然后将文件写到输入流里面就行,关键配置还是在struts.xml这个配置文件里配置:
FileDownloadAction代码如下:
public class FileDownloadAction extends ActionSupport
{
public InputStream getDownloadFile()
{
return ServletActionContext.getServletContext().getResourceAsStream("upload/通讯录2012年9月4日.xls");
}
@Override
public String execute() throws Exception
{
return SUCCESS;
}
}
我们看,这个action只是定义了一个输入流,然后为其提供getter方法就行,接下来我们看看struts.xml的配置文件:
<action name="fileDownload" class="com.xiaoluo.struts2.FileDownloadAction">
<result name="success" type="stream">
<param name="contentDisposition">attachment;filename="通讯录2012年9月4日.xls"</param>
<param name="inputName">downloadFile</param>
</result>
</action>
struts.xml配置文件有几个地方我们要注意,首先是result的类型,以前我们定义一个action,result那里我们基本上都不写type属性,因为其默认是请求转发(dispatcher)的方式,除了这个属性一般还有redirect(重定向)等这些值,在这里因为我们用的是文件下载,所以type一定要定义成stream类型,告诉action这是文件下载的result,result元素里面一般还有param子元素,这个是用来设定文件下载时的参数,inputName这个属性就是得到action中的文件输入流,名字一定要和action中的输入流属性名字相同,然后就是contentDisposition属性,这个属性一般用来指定我们希望通过怎么样的方式来处理下载的文件,如果值是attachment,则会弹出一个下载框,让用户选择是否下载,如果不设定这个值,那么浏览器会首先查看自己能否打开下载的文件,如果能,就会直接打开所下载的文件,(这当然不是我们所需要的),另外一个值就是filename这个就是文件在下载时所提示的文件下载名字。在配置完这些信息后,我们就能过实现文件的下载功能了。
struts2多文件上传:
其实多文件上传和单文件上传原理一样,单文件上传过去的是单一的File,多文件上传过去的就是一个List<File>集合或者是一个File[]数组,首先我们来看一下前端jsp部分的代码,这里我用到了jquery来实现动态的添加文件下载框以及动态的删除下载框:
<script type="text/javascript" src="script/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function()
{
$("#button").click(function()
{
var html = $("<input type='file' name='file'>");
var button = $("<input type='button' name='button' value='删除'><br>");
$("#body div").append(html).append(button);
button.click(function()
{
html.remove();
button.remove();
})
})
})
</script>
</head>
<body id="body">
<form action="fileUpload2.action" method="post" enctype="multipart/form-data">
username: <input type="text" name="username"><br>
file: <input type="file" name="file">
<input type="button" value="添加" id="button"><br>
<div></div>
<input type="submit" value="submit">
</form>
</body>
file的名字必须都命名成file才行,然后处理多文件上传的action代码如下:
public class FileUploadAction2 extends ActionSupport
{
private String username;
//这里用List来存放上传过来的文件,file同样指的是临时文件夹中的临时文件,而不是真正上传过来的文件
private List<File> file;
//这个List存放的是文件的名字,和List<File>中的文件相对应
private List<String> fileFileName;
private List<String> fileContentType;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public List<File> getFile()
{
return file;
}
public void setFile(List<File> file)
{
this.file = file;
}
public List<String> getFileFileName()
{
return fileFileName;
}
public void setFileFileName(List<String> fileFileName)
{
this.fileFileName = fileFileName;
}
public List<String> getFileContentType()
{
return fileContentType;
}
public void setFileContentType(List<String> fileContentType)
{
this.fileContentType = fileContentType;
}
@Override
public String execute() throws Exception
{
String root = ServletActionContext.getServletContext().getRealPath("/upload");
for(int i = 0; i < file.size(); i++)
{
InputStream is = new FileInputStream(file.get(i));
OutputStream os = new FileOutputStream(new File(root, fileFileName.get(i)));
byte[] buffer = new byte[500];
@SuppressWarnings("unused")
int length = 0;
while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}
os.close();
is.close();
}
return SUCCESS;
}
}
这样同样将其写到一个输出流里面,这样我们就可以在文件夹里看到上传的多个文件了
Ⅱ struts2 上传文件得到的是.tmp 怎么得到原有文件名
我上传的文件还没有出现过类似问题,用的是第三方类库fileupload上传的!
Ⅲ struts2上传文件的类型去哪里找
struts2是根据contentType来限制的,并不是文件的扩展名
比如我想仅上传image/png,image/gif,image/jpeg这三种文件类型
第一种方法是通过javascript校验来限制,这个比较简单,获取input的value然后截取扩展名进行判断即可
第二种是根据struts2自带的fileupload拦截器中提供的allowedTypes来进行限制,步骤如下:
1 配置fileupload拦截器
struts2的defaultStack中已经含有fileupload拦截器,如果想加入allowedTypes参数,需要从新写一个defaultstack ,拷贝过来修改一下即可:
<interceptor-stack name="myDefaultStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="alias"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="prepare"/>
<interceptor-ref name="chain"/>
<interceptor-ref name="debugging"/>
<interceptor-ref name="profiling"/>
<interceptor-ref name="scopedModelDriven"/>
<interceptor-ref name="modelDriven"/>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
<interceptor-ref name="checkbox"/>
<interceptor-ref name="staticParams"/>
<interceptor-ref name="actionMappingParams"/>
<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
仅修改代码中的
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
上面配置的是上传文件类型的限制,其实共有两个参数
maximumSize (可选) - 这个拦截器允许的上传到action中的文件最大长度(以byte为单位). 注意这个参数和在webwork.properties中定义的属性没有关系,默认2MB
allowedTypes (可选) - 以逗号分割的contentType类型列表(例如text/html),这些列表是这个拦截器允许的可以传到action中的contentType.如果没有指定就是允许任何上传类型.
2 jsp页面定义如下(testFileUpload.jsp)
<s:form action="testFileUpload" method="post" enctype="multipart/form-data">
<s:file name="file"theme="simple"/>
<s:fielderror name="file"></s:fielderror>
<s:submit/>
</s:form>
3 后台的action声明如下(我用的是struts2的注解进行action配置)
public class TestFileUploadAction extends ActionSupport{
private File file;
private String fileContentType;
private String fileFileName;
@Action(
value = "testFileUpload", results = {
@Result(name = "input", location = "/testFileUpload.jsp"),
@Result(name = "success", location = "/testFileUploadSuccess.jsp")
}
)
public String execute() {
return SUCCESS;
}
get/set......
}
注意:如果jsp中file的name="xxx",那么后台action中的属性要做相应更改为
private File xxx;
private String xxxContentType;
private String xxxFileName;
同时注意大小写一定要一致
4 定义错误文件类型的消息提示,这个需要用到struts2的资源文件,在struts.properties文件中加入
struts.custom.i18n.resources=globalMessages
globalMessages对应着资源文件名
5 在源文件夹下定义资源文件globalMessages.properties,并在里面加入如下信息:
struts.messages.error.content.type.not.allowed=upload file contenttype is invalidate
这里稍作说明(拷贝一下struts2的帮助):
如果你的action实现了ValidationAware接口(如果action继承了ActionSupport,那么就相当于实现了ValidationAware),这个拦截器就可以添加几种字段错误.这些错误信息是基于存储在struts-messages.properties文件中的一些i18n值,这个文件是所有i18n请求的默认文件.你可以在自己消息文件的复写以下key的消息文字
struts.messages.error.uploading - 文件不能上传的通用错误信息
struts.messages.error.file.too.large - 上传文件长度过大的错误信息
struts.messages.error.content.type.not.allowed - 当上传文件不符合指定的contentType
以上配置完毕后,测试一下,对于非法的contentType,例如xxx.log这个文件的的contentType是pplication/octet-stream
会给出提示:upload file contenttype is invalidate
'.a' : 'application/octet-stream',
'.ai' : 'application/postscript',
'.aif' : 'audio/x-aiff',
'.aifc' : 'audio/x-aiff',
'.aiff' : 'audio/x-aiff',
'.au' : 'audio/basic',
'.avi' : 'video/x-msvideo',
'.bat' : 'text/plain',
'.bcpio' : 'application/x-bcpio',
'.bin' : 'application/octet-stream',
'.bmp' : 'image/x-ms-bmp',
'.c' : 'text/plain',
'.cdf' : 'application/x-cdf',
'.cdf' : 'application/x-netcdf',
'.cpio' : 'application/x-cpio',
'.csh' : 'application/x-csh',
'.css' : 'text/css',
'.dll' : 'application/octet-stream',
'.doc' : 'application/msword',
'.dot' : 'application/msword',
'.dvi' : 'application/x-dvi',
'.eml' : 'message/rfc822',
'.eps' : 'application/postscript',
'.etx' : 'text/x-setext',
'.exe' : 'application/octet-stream',
'.gif' : 'image/gif',
'.gtar' : 'application/x-gtar',
'.h' : 'text/plain',
'.hdf' : 'application/x-hdf',
'.htm' : 'text/html',
'.html' : 'text/html',
'.ief' : 'image/ief',
'.jpe' : 'image/jpeg',
'.jpeg' : 'image/jpeg',
'.jpg' : 'image/jpeg',
'.js' : 'application/x-javascript',
'.ksh' : 'text/plain',
'.latex' : 'application/x-latex',
'.m1v' : 'video/mpeg',
'.man' : 'application/x-troff-man',
'.me' : 'application/x-troff-me',
'.mht' : 'message/rfc822',
'.mhtml' : 'message/rfc822',
'.mif' : 'application/x-mif',
'.mov' : 'video/quicktime',
'.movie' : 'video/x-sgi-movie',
'.mp2' : 'audio/mpeg',
'.mp3' : 'audio/mpeg',
'.mpa' : 'video/mpeg',
'.mpe' : 'video/mpeg',
'.mpeg' : 'video/mpeg',
'.mpg' : 'video/mpeg',
'.ms' : 'application/x-troff-ms',
'.nc' : 'application/x-netcdf',
'.nws' : 'message/rfc822',
'.o' : 'application/octet-stream',
'.obj' : 'application/octet-stream',
'.oda' : 'application/oda',
'.p12' : 'application/x-pkcs12',
'.p7c' : 'application/pkcs7-mime',
'.pbm' : 'image/x-portable-bitmap',
'.pdf' : 'application/pdf',
'.pfx' : 'application/x-pkcs12',
'.pgm' : 'image/x-portable-graymap',
'.pl' : 'text/plain',
'.png' : 'image/png',
'.pnm' : 'image/x-portable-anymap',
'.pot' : 'application/vnd.ms-powerpoint',
'.ppa' : 'application/vnd.ms-powerpoint',
'.ppm' : 'image/x-portable-pixmap',
'.pps' : 'application/vnd.ms-powerpoint',
'.ppt' : 'application/vnd.ms-powerpoint',
'.ps' : 'application/postscript',
'.pwz' : 'application/vnd.ms-powerpoint',
'.py' : 'text/x-python',
'.pyc' : 'application/x-python-code',
'.pyo' : 'application/x-python-code',
'.qt' : 'video/quicktime',
'.ra' : 'audio/x-pn-realaudio',
'.ram' : 'application/x-pn-realaudio',
'.ras' : 'image/x-cmu-raster',
'.rdf' : 'application/xml',
'.rgb' : 'image/x-rgb',
'.roff' : 'application/x-troff',
'.rtx' : 'text/richtext',
'.sgm' : 'text/x-sgml',
'.sgml' : 'text/x-sgml',
'.sh' : 'application/x-sh',
'.shar' : 'application/x-shar',
'.snd' : 'audio/basic',
'.so' : 'application/octet-stream',
'.src' : 'application/x-wais-source',
'.sv4cpio': 'application/x-sv4cpio',
'.sv4crc' : 'application/x-sv4crc',
'.swf' : 'application/x-shockwave-flash',
'.t' : 'application/x-troff',
'.tar' : 'application/x-tar',
'.tcl' : 'application/x-tcl',
'.tex' : 'application/x-tex',
'.texi' : 'application/x-texinfo',
'.texinfo': 'application/x-texinfo',
'.tif' : 'image/tiff',
'.tiff' : 'image/tiff',
'.tr' : 'application/x-troff',
'.tsv' : 'text/tab-separated-values',
'.txt' : 'text/plain',
'.ustar' : 'application/x-ustar',
'.vcf' : 'text/x-vcard',
'.wav' : 'audio/x-wav',
'.wiz' : 'application/msword',
'.wsdl' : 'application/xml',
'.xbm' : 'image/x-xbitmap',
'.xlb' : 'application/vnd.ms-excel',
'.xls' : 'application/excel',
'.xls' : 'application/vnd.ms-excel',
'.xml' : 'text/xml',
'.xpdl' : 'application/xml',
'.xpm' : 'image/x-xpixmap',
'.xsl' : 'application/xml',
'.xwd' : 'image/x-xwindowmp',
'.zip' : 'application/zip',
Ⅳ java struts2 怎么获取从jsp传过来的多个file
在action中声明三个变量,然年后生成get、set方法
privateFilefile;
privateStringfileFileName;
privateStringfileContentType;
注意,这三个变量的名字不能乱写,必须是这个格式的。如果你在表单的名字叫image,那个变量名字就应该是:
privateFileimage;
privateStringimageFileName;
privateStringimageContentType;
/**************************华丽的分割线**************************************/
第一个就是药品上传的文件的引用,第二个是要上传文件的名字,是三个是要上传文件的类型。
然后就可以通过输出流进行上传了。
Ⅳ 为什么Struts2上传文件之后扩展名变成了tmp,如何取得文件正确的扩展名
在action中获取到上传文件名利用上传文件名来存储就不会出现tmp结尾文件了
Ⅵ Struts2怎么获取到 上传文件的源路径
必要前提:
a.表单method必须是post;
b.enctype取值必须是multipart/form-data;
c.提供文件选择域。定义参数接收
File photo; // 接受上传的文件 File接受
String photoFileName; // 上传的文件名 文件name属性+FileName,
String photoContentType; // 文件的MIME类型 文件name属性+ContentType
例如:
action中
Ⅶ 用Struts2做文件上传时,前台js获得文件对象,文件名,文件内容类型。怎么在action中获得文件对象
从视图层传入action的所有对象都封装在mapper对象中。。。
Ⅷ struts2.0怎么实现上传文件
一、创建jsp页面:
注意!要上传文件,表单必须添加 enctype 属性,如下: enctype="multipart/form-data"
index.jsp 代码如下:
<%@ 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>
<!-- 注意!表单必须添加 enctype 属性,值为"multipart/form-data" -->
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
二、创建Action类:
1. 添加三个私有字段,并添加相应的get,set方法。
private File file; ——上传的文件,变量名对应页面上"file"input的name属性值。类型为java.io.File
private String fileContentType;——上传文件的格式类型名,变量名格式为:页面上"file"input的name属性值+ContentType
private String fileFileName——上传的文件名,变量名格式为:页面上"file"input的name属性值+fileFileName。
2. 使用struts2提供的FileUtils类拷贝进行文件的拷贝。FileUtils类位于org.apache.commons.io包下。
3. 在项目目录下的WebContent目录下添加 upload 文件夹,用于存放客户端上传过来的文件,对应第15行代码。
Upload.java代码如下:
1 import java.io.File;
2 import java.io.IOException;
3 import org.apache.commons.io.FileUtils;
4 import org.apache.struts2.ServletActionContext;
5 import com.opensymphony.xwork2.ActionSupport;
6
7 public class Upload extends ActionSupport{
8 private File file;
9 private String fileContentType;
10 private String fileFileName;
11
12 @Override
13 public String execute() throws Exception {
14 //得到上传文件在服务器的路径加文件名
15 String target=ServletActionContext.getServletContext().getRealPath("/upload/"+fileFileName);
16 //获得上传的文件
17 File targetFile=new File(target);
18 //通过struts2提供的FileUtils类拷贝
19 try {
20 FileUtils.File(file, targetFile);
21 } catch (IOException e) {
22 e.printStackTrace();
23 }
24 return SUCCESS;
25 }
26
27 //省略get,set方法...........
28
29 }
三、在struts.xml中添加相应的配置代码。
struts.xml代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="upload" class="Upload">
<result>index.jsp</result>
</action>
</package>
</struts>
四、测试。
启动服务器,进入index页面。
选择一改图片,点击上传提交表单。
打开upload文件夹(注意,这里指的是web服务器下的目录,如我用的web服务器是tomcat安装在电脑D盘,项目名称为“Struts2Upload”那么其路径为:D:\apache-tomcat-7.0.40\webapps\Struts2Upload\upload)可以看到刚才选中的图片已经上传到该目录下了。
上传多个文件
一、修改页面文件
增加继续添加按钮和 addfile() 方法,让页面可以通过javascript增加 input 标签。
修改后的 index.jsp代码如下:
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <script type="text/javascript">
8 //添加javascript方法 addfile() 在页面中境加input标签、
9 function addfile(){
10 var file = document.createElement("input");
11 file.type="file";
12 file.name="file";
13 document.getElementById("fileList").appendChild(file);
14 document.getElementById("fileList").appendChild(document.createElement("br"));
15 }
16 </script>
17 <title>Insert title here</title>
18 </head>
19 <body>
20 <!-- 注意!表单必须添加 enctype 属性,值为"multipart/form-data" -->
21 <form action="upload.action" method="post" enctype="multipart/form-data">
22 <div id="fileList">
23 <input type="file" name="file" /><br/>
24 </div>
25 <!-- 添加继续添加按钮,点击按钮调用addfile() -->
26 <input type="button" value="继续添加" onclick="addfile()" />
27 <input type="submit" value="上传"/>
28 </form>
29 </body>
30 </html>
二、修改Action类
1. 把三个私有字段(file,fileContentType,fileFileName)的类型更改为数组或集合类型。并添加相应的get,set方法。
2. 通过循环来上传多个文件。
修改后的Upload.java代码如下:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Upload extends ActionSupport{
//把这三个字段类型更改为数组或集合
private File[] file;
private String[] fileContentType;
private String[] fileFileName;
@Override
public String execute() throws Exception {
//通过循环来上传多个文件
for(int i=0;i<file.length;i++){
//得到上传文件在服务器的路径加文件名
String target=ServletActionContext.getServletContext().getRealPath("/upload/"+fileFileName[i]);
//获得上传的文件
File targetFile=new File(target);
//通过struts2提供的FileUtils类拷贝
try {
FileUtils.File(file[i], targetFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return SUCCESS;
}
//省略set,get方法...................
}
三、测试
1. 启动服务器,打开index.jsp页面。点击继续添加,添加两个input。同时上传三张图片。
2. 点击上传提交表单。打开upload文件夹,可以看到刚才选中的三张图片已经上传到该目录下了。
参考资料http://www.cnblogs.com/likailan/p/3330465.html
Ⅸ struts2上传文件的时候,为什么我获取不到上传文件的名称
检查几个地方:
1、上传控件的name和后台对应的属性名是否一致。
2、是否加入fileupload拦截器。
3、文件是否过大和不符合后缀名。