java中Struts2文件上传问题详解
作者:hebedich 发布时间:2023-12-16 10:27:54
首先是网页部分,upload_file.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>Upload File</title>
</head>
<body>
<form action="UploadFile" method="post" enctype="multipart/form-data">
<!--文件域-->
<input type="file" name="source" /> <input type="submit" value="上传">
</form>
</body>
</html>
上传文件的表单,metho必须设置成post,enctype必须设置成multipart/form-data。
从上面代码中可以看到这个表单提交给了UploadFile这个action来处理,那我们在struts.xml里面配置如下:
<action name="UploadFile" class="com.lidi.action.UploadAction">
<result name="success">/uploadResult.jsp</result>
<!--fileUpload * ,可用于限制上传文档的类型和文档大小 -->
<interceptor-ref name="fileUpload">
<!-- 限制文件大小20M,单位为字节 -->
<param name="maximumSize">20971520</param>
</interceptor-ref>
<!--默认 * ,必须声明在fileUpload * 之后 -->
<interceptor-ref name="defaultStack" />
</action>
fileUpload * ,用于设置上传路径,限制文件类型和大小。
关于限制文件大小,光有<param name="maximumSize">是不行的,还必须在<struts>标签下添加
<constant name="struts.multipart.maxSize" value="21000000"/>
这行代码表示整个项目所有要上传文件的地方允许上传的文件大小的最大值,也就是说这个项目里上传的任何单个文件大小不能超过21000000字节(约20M),如果项目中不添加这行代码,则默认允许上传的文件大小最大为2M,所以这也是突破struts2只能上传2M文件的限制的方法。
关于限制文件类型,如果需要限制为图片文件,则<interceptor>可以这样配置
<!-- 设置只允许上传图片文件 -->
<intercepter-ref name="fileUpload">
<param name="allowedTypes">image/bmp, image/x-png, image/gif, image/jpeg</param>
</intercepter-ref>
<interceptor-ref name="defaultStack" />
<param name="allowedTypes">标签中的值都是文件的MIME类型,常用文件的MIME类型可以在%TOMCAT_HOME%\conf\web.xml中找到。
如果要限制为word文件,则可以<interceptor>可以这样配置
<!-- 设置只允许上传word文档 -->
<intercepter-ref name="fileUpload">
<param name="allowedTypes">application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
</intercepter-ref>
<interceptor-ref name="defaultStack" />
然而我感觉这样来限制文件类型,不如用javascript在前端实现限制。
接下来写UploadAction,UploadAction必需的私有属性是source,这是和upload_file.jsp里面文件域的name属性是一致,就是说文件域的name属性值为source,则UploadAction中必需有私有属性source,另外,还有两个比较重要的私有属性:
private String sourceFileName; //待上传文件的文件名
private String sourceContentType; //待上传文件的文件类型
这两个变量名的格式就是前面的前缀source和upload_file.jsp中的文件域的name属性相同。
综合来说,就是,比如upload_file.jsp中文件域的name = “abc”,则Action中就需要这样定义
private File abc;
private String abcFileName;
private String abcContentType;
abc会自动获取要上传的文件对象,abcFileName自动获取文件名,abcContentType自动获取文件类型。
关于上传路径,是我要重点说一下的。
如果是上传到绝对路径,那还挺好搞的,但如果要上传到项目根目录下的upload文件夹呢,怎么获得这个upload文件夹的完整路径?
我尝试过使用
ServletActionContext.getServletContext().getRealPath("/upload");
但返回了null。也用过
ServletActionContext.getRequest().getRealPath("/upload");
还是返回了null。但在网上查下这个问题,很多人都推荐这么写,证明可能某些情况下这样写确实是可行的,但也有跟我一样返回null的人,他们同时推荐了一种新的方法,就是让UploadAction实现ServletContextAware接口。具体做法如下:
public class UploadAction extends ActionSupport implements ServletContextAware {
/**
* 省略其它代码...
*/
private ServletContext context;
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
@Override
public void setServletContext(ServletContext context) {
this.context = context;
}
}
然后使用
String path = context.getRealPath("/upload");// 重要:斜杠不能少
获得upload文件夹的路径。然后执行上传:
/*将文件上传到upload文件夹下*/
File savefile = new File(path, sourceFileName);
FileUtils.copyFile(source, savefile);
我个人是比较推荐这种方法的,因为这种方法好像规避了当项目被打包转移到其它环境时也能保证获得正确的路径。
后面贴上UploadAction的完整代码UploadAction.java
package com.lidi.action;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport implements ServletContextAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private File source;// 待上传文件
private String sourceFileName;// 待上传文件的文件名
private String sourceContentType; // 待上传文件的文件类型
private ServletContext context; // 重要
/* 重要 */
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
/* getters & setters */
public File getSource() {
return source;
}
public void setSource(File source) {
this.source = source;
}
public String getSourceFileName() {
return sourceFileName;
}
public void setSourceFileName(String sourceFileName) {
this.sourceFileName = sourceFileName;
}
public String getSourceContentType() {
return sourceContentType;
}
public void setSourceContentType(String sourceContentType) {
this.sourceContentType = sourceContentType;
}
@Override
public void setServletContext(ServletContext context) {
this.context = context;
}
public String execute() throws IOException {
/*获取存放上传文件的路径:项目根目录upload文件夹*/
String path;
path = context.getRealPath("/upload");// 重要:斜杠不能少
System.out.println(path);
/*将文件上传到upload文件夹下*/
File savefile = new File(path, sourceFileName);
FileUtils.copyFile(source, savefile);
System.out.println(savefile.getAbsolutePath());
return SUCCESS;
}
}
上传结果页uploadResult.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML>
<html>
<head>
<title>Upload Result</title>
</head>
<body>
<p>文件名:<s:property value="sourceFileName" /></p>
<p>文件类型:<s:property value="sourceContentType" /></p>
<p>文件:<a href="upload/<s:property value="sourceFileName" />"><s:property value="sourceFileName" /></a></p>
</body>
</html>
以上所述就是本文的全部内容了,希望大家能够喜欢。


猜你喜欢
- 本文实例讲述了Android编程判断网络连接是否可用的方法。分享给大家供大家参考,具体如下:为了提高用户体验,我们在开发 android 应
- Android application捕获崩溃异常怎么办?通用 application1、收集所有 avtivity 用于彻底退出应用2、捕
- 问题介绍:用二维数组表示一个迷宫,设置迷宫起点和终点,输出迷宫中的一条通路实现思路:二维数组表示迷宫:0表示路且未走过、1表示墙、2表示通路
- 我使用的版本是SpringBoot 2.6.4可以实现注入不同的库连接或是动态切换库<parent>
- 本文实例为大家分享了Java实现简单GUI登录和注册界面的具体代码,供大家参考,具体内容如下先看效果图:登陆界面:注册界面:实现代码如下:一
- 前言以前我们还需要手写数据库设计文档、现在可以通过引入screw核心包来实现Java 数据库文档一键生成。话不多说、直接上代码演示。支持的数
- 这篇文章需要一定Vue和SpringBoot的知识,分为两个项目,一个是前端Vue项目,一个是后端SpringBoot项目。后端项目搭建我使
- 一、maven * 搭建使用Nexus进行搭建,网上教程很多,不多赘述了。二、gradle配置在build.gradle文件的根节点中添加以下
- 1.@Value注解@Value注解的源码,如下所示@Target({ElementType.FIELD, ElementType.METH
- 本文实例讲述了Android编程实现将压缩数据库文件拷贝到安装目录的方法。分享给大家供大家参考,具体如下:public void copyZ
- 这篇文章主要介绍了Java String的intern用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,
- DeferredResult的超时处理,采用委托机制,也就是在实例DeferredResult时给予一个超时时长(毫秒),同时在onTime
- 本文实例为大家分享了C#实现简单串口通讯的具体代码,供大家参考,具体内容如下参数设置界面代码:using System;using Syst
- 今日遇到一个问题:springboot需要获取到一个自定义名称文件夹下的静态资源(图片等),并且文件夹的路径不在classPath下面,而是
- 平面区域填充算法是计算机图形学领域的一个很重要的算法,区域填充即给出一个区域的边界(也可以是没有边界,只是给出指定颜色),要求将边界范围内的
- 最新更新的Flyme6整体效果不错,动画效果增加了很多了,看了看flyme6的Viewpager指示器,觉得有点意思,就模仿写了一下,整体效
- private string CheckCidInfo(string cid) &
- 配置文件中使用${}注入值方式在springboot中使用System.setProperty设置参数user: user-na
- using System;using System.Collections.Generic;using System.Web.Script.
- 对于大文件的处理,无论是用户端还是服务端,如果一次性进行读取发送、接收都是不可取,很容易导致内存问题。所以对于大文件上传,采用切块分段上传,