Struts2学习笔记(十六) 文件上传(File Upload)

使用jsp/Servlet实现文件上传

在我们的web应用中,文件上传是一项非常常见的功能。以前我学习php的时候也用php写过文件上传,不过php中实现起来比较方便,只需要从全局变量$_FILES中获取到上传文件的临时存放路径等信息,再把它拷贝到目标地址并重命名就可以了。在Java中要实现文件上传要稍微复杂一点。我们需要通过request的getInputStream方法来获取到相关的输入流,然后在从输入流中读取文件内容,悲剧的就是在输入流中加入了一些信息,比如文件名之类的。所以我们要想从输入流中获取到纯正的文件内容,还需要我们做一些处理。

比如我们有一个文本文件,里面只有一句话:hello word,那么如果我们在文件上传时直接将输入流中的数据写入到文件中,那么会多出许多额外的信息。

------WebKitFormBoundaryEvAVDYPz4OMMZU92

Content-Disposition:form-data; name="file"; filename="新建文本文档.txt"

Content-Type: text/plain

hello world

------WebKitFormBoundaryEvAVDYPz4OMMZU92—

这些信息有些对我们有用,比如我们可以通过第二行来获取到上传文件的名字,第三行可以获取到文件的类型。但是实际文件的内容应该只有hello world一行,也就是说前面的5行和后面的一行都是多余的,不应该写进文件。下面我们就对这些“多余”的信息做一些处理。

首先我们新建一个Servlet来处理文件内容:

public class AcceptServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取输入流 ServletInputStream in = request.getInputStream(); // 缓冲字节数组 byte[] b = new byte[1024]; // 读取第一个行信息(包含分隔符) int len = in.readLine(b, 0, b.length); String f = new String(b, 0, len); len = in.readLine(b, 0, b.length); // 从第二行中提取文件名 String fileName = new String(b, 0, len); fileName = fileName.substring(0, fileName.lastIndexOf("\"")); fileName = fileName.substring(fileName.lastIndexOf("\"") + 1); // 提取文件后缀 String suffix = fileName.substring(fileName.lastIndexOf(".")); // 剔除两行无用信息 in.readLine(b, 0, b.length); in.readLine(b, 0, b.length); // 创建文件输出流 FileOutputStream out = new FileOutputStream("d:/" + System.currentTimeMillis() + suffix); // 读取数据 while ((len = (in.readLine(b, 0, b.length))) != -1) { String f1 = new String(b, 0, len); // 如果已经到达结尾,则不写入(最后一行包含分隔符) if (f1.contains(f.trim())) { break; } out.write(b, 0, len); } out.close(); in.close(); PrintWriter p = response.getWriter(); p.print("success"); } }

然后我们新建一个input.jsp

<body>

<form action="AcceptServlet"method="post" enctype="multipart/form-data">

<input type="file" name="file">

<input type="submit"value="submit">

</form>

</body>

我们在浏览器中测试一下:

提交之后,页面显示”success”,我们到d盘下打开文件,查看文件内容:

多次测试,每次选择不同的文件类型,比如图片,压缩文件,exe程序。均能正确上传。

使用Struts2实现文件上传

虽然我们在上面的例子中通过一些简单的处理,能够实现文件的上传,但是这有局限性。比如可能在Linux系统中或者不同的浏览器中,输入流中的附加信息的格式会有所不同。那么Struts2提供的文件上传功能将更加具有通用性和易用性,我们无需关注底层是何种实现,Struts2会给我一个统一的结果。

Struts2中的文件上传功能是通过将Commons FileUpload开源库集成进来实现的,这个工作有defaultStack拦截器栈中的fileUpload拦截器来完成。我们查看文档可以知道该拦截器的实现类是org.apache.struts2.interceptor. FileUploadInterceptor.我们查看该拦截器的intercept方法的源码:

public String intercept(ActionInvocation invocation) throws Exception { ActionContext ac = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); if (!(request instanceof MultiPartRequestWrapper)) { if (LOG.isDebugEnabled()) { ActionProxy proxy = invocation.getProxy(); LOG.debug(getTextMessage("struts.messages.bypass.request", new Object[]{proxy.getNamespace(), proxy.getActionName()}, ac.getLocale())); } return invocation.invoke(); } ValidationAware validation = null; Object action = invocation.getAction(); if (action instanceof ValidationAware) { validation = (ValidationAware) action; } MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request; if (multiWrapper.hasErrors()) { for (String error : multiWrapper.getErrors()) { if (validation != null) { validation.addActionError(error); } if (LOG.isWarnEnabled()) { LOG.warn(error); } } } // bind allowed Files Enumeration fileParameterNames = multiWrapper.getFileParameterNames(); while (fileParameterNames != null && fileParameterNames.hasMoreElements()) { // get the value of this input tag String inputName = (String) fileParameterNames.nextElement(); // get the content type String[] contentType = multiWrapper.getContentTypes(inputName); if (isNonEmpty(contentType)) { // get the name of the file from the input tag String[] fileName = multiWrapper.getFileNames(inputName); if (isNonEmpty(fileName)) { // get a File object for the uploaded File File[] files = multiWrapper.getFiles(inputName); if (files != null && files.length > 0) { List<File> acceptedFiles = new ArrayList<File>(files.length); List<String> acceptedContentTypes = new ArrayList<String>(files.length); List<String> acceptedFileNames = new ArrayList<String>(files.length); String contentTypeName = inputName + "ContentType"; String fileNameName = inputName + "FileName"; for (int index = 0; index < files.length; index++) { if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) { acceptedFiles.add(files[index]); acceptedContentTypes.add(contentType[index]); acceptedFileNames.add(fileName[index]); } } if (!acceptedFiles.isEmpty()) { Map<String, Object> params = ac.getParameters(); params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()])); params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()])); params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()])); } } } else { if (LOG.isWarnEnabled()) { LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new Object[]{inputName}, ac.getLocale())); } } } else { if (LOG.isWarnEnabled()) { LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new Object[]{inputName}, ac.getLocale())); } } } // invoke action return invocation.invoke(); }

从中我们大致可以看出,它首先会判断请求中是否包含文件上传,如果包含,那么就将这些要上传的文件转化为对应的File对象,并且将这些文件对应的ContentType和FileName一并提取出来。它将这些对象设置到了请求参数中,由于fileUpload拦截器在parameters拦截器之前,因此它添加到请求中的这些参数将会被parameters拦截器设置到相应的Action类属性上。从源代码中我们也可以看出,对于文件上传,Action中的一些属性的命名是被写死了。比如ContentType,那么Action类中对应的属性名必须是表单中file表单的name属性值加上“ContentType”。文件名也是表单name属性值加上”FileName”。

从源代码中我们也可以看出最后放入到请求参数中的都是数组类型,也就是Struts2也支持多文件的上传。那么对应的多文件上传时我们Action类中属性也需要设置为数组类型。Struts2能够自动将这些属性给我吗设置上。这个拦截器还有三个属性,通过设置这些属性的值,可以给我吗简化一些操作:

(1)maximumSize :上传文件的最大长度(字节为单位),默认2mb.

(2)allowedTypes :允许上传的文件内容的类型,个类型之间使用逗号隔开

(3)allowedExtensions :允许上传的文件的后缀列表,多个用逗号隔开

单文件上传实例:

public class UploadAction extends ActionSupport { private File attachment; private String attachmentContentType; private String attachmentFileName; public File getAttachment() { return attachment; } public void setAttachment(File attachment) { this.attachment = attachment; } public String getAttachmentContentType() { return attachmentContentType; } public void setAttachmentContentType(String attachmentContentType) { this.attachmentContentType = attachmentContentType; } public String getAttachmentFileName() { return attachmentFileName; } public void setAttachmentFileName(String attackmentFileName) { this.attachmentFileName = attackmentFileName; } @Override public String execute() throws Exception { if (attachment != null) { File out = new File("d:/" + attachmentFileName); attachment.renameTo(out); } return super.execute(); } }

input.jsp

<form action="upload.action" method="post" enctype="multipart/form-data">

<input type="file" name="attachment"/>

<input type="submit"value="submit"/>

</form>

测试:

提交后打开上传后的文件:

这里还遇到一点小问题,为了简便,我在jsp页面中只是使用了简单的html,结果发现如果想在页面输出中文的话,那么这些中文全部会编程问号。首先怀疑编码问题,在<head>中加了<metahttp-equiv="Content-Type" content="text/html;charset=utf-8" />

还是没效果。后来直接在页面中输入中文,提示无法保存保存中文,因为页面编码是iso-8859-1,查看myeclipse的设置发现我们已经将Jsp页面的编码默认设置为了utf8,为啥还提示说是西欧编码呢,后来在页面中加入了<%@ page language="java" import="java.util.*"pageEncoding="UTF-8"%>,问题解决。原来如果我们在jsp页面中不加这个指令,那么默认还是会使用西欧编码。

多文件上传实例

public class UploadAction extends ActionSupport { private File[] attachment; private String[] attachmentContentType; private String[] attachmentFileName; //get/set省略 @Override public String execute() throws Exception { if (attachment != null && attachment.length > 0) { for (int i = 0; i < attachment.length; i++) { File out = new File("d:/" + attachmentFileName[i]); attachment[i].renameTo(out); } } return SUCCESS; }

Input.jsp

form action="upload.action" method="post" enctype="multipart/form-data">

<input type="file" name="attachment"/><br>

<input type="file" name="attachment"/><br>

<input type="file" name="attachment"/><br>

<input type="submit" value="submit"/>

</form>

在这里也遇到一个问题,就是上传文件大小的问题,Struts2默认允许的文件上传大小为2M,我们前面学习到fileUpload拦截器中可以指定文件上传的大小:

<action name="upload" class="action.UploadAction">

<interceptor-ref name="fileUpload">

<param name="maximumSize">1024000</param>

</interceptor-ref>

<interceptor-ref name="basicStack"></interceptor-ref>

<result name="success">/success.jsp</result>

<result name="input">/input.jsp</result>

</action>

但是这样配置之后,当上传文件超过靓照的时候还是会报错。这是因为Struts2中有一个常量表示文件上传的大小,只有当fileUpload拦截器中设置的值小于这个常量的值时,拦截器设置的值才起作用。因此我们还需要修改这个常量的值:

<constant name="struts.multipart.maxSize" value="10240000" />

而fileUpload拦截器中关于文件大小的默认值就是这个常量的值!

在多文件上传中,我们的Action成员属性除了使用数组之外还可以使用List,不过需要我们手动给他们初始化才能发挥作用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值