• 一、配置SpringMVC
  • 二、单文件与多文件上传
  • 三、多文件上传
  • 四、带参数上传

一、配置SpringMVC
在spring.xml中配置:

    <!-- springmvc文件上传需要配置的节点-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="-1"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="false"/>
<property name="uploadTempDir" value="/statics/document/tempdir"/>
<!--<property name="maxInMemorySize" value="104857600"/>-->
</bean>

其中属性详解:
defaultEncoding="UTF-8" 是请求的编码格式,默认为iso-8859-1
maxUploadSize="-1 是上传文件的大小,单位为字节 -1表示无限制
uploadTempDir="fileUpload/temp" 为上传文件的临时路径


二、单文件与多文件上传
1、单文件上传
jsp:

<body>
<h2>文件上传实例</h2> <form action="fileUpload.html" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="提交">
</form> </body>

注意要在form标签中加上enctype="multipart/form-data"表示该表单是要处理文件的!

controller:

    @RequestMapping("fileUpload")
public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
// 重定向
return "redirect:/list.html";
}

注意RequestParam参数中value的名字要与jsp中的相互匹配,否则会找不到返回空指针
transferTo是存储文件的核心方法,但是这个方法同一个文件只能使用一次,不能使用第二次,否则tomcat服务器会报500的错误

MultipartFile类常用的一些方法:

String getContentType()//获取文件MIME类型
InputStream getInputStream()//后去文件流
String getName() //获取表单中文件组件的名字
String getOriginalFilename() //获取上传文件的原名
long getSize() //获取文件的字节大小,单位byte
boolean isEmpty() //是否为空
void transferTo(File dest)//保存到一个目标文件中。


三、多文件上传
与上面的相同只不过是form里面多创建几个input
如果需要使用一个标签控件上传多个文件,需要使用js插件uploadify
博主备份的下载地址(该版本为flash版本,不推荐,HTML5版本请自行去官网下载):uploadify.rar(解压密码:crowsong.xyz): http://waternote.ctfile.net/fs/2276132-372974128   
jsp:

<body>
<h2>上传多个文件 实例</h2> <form action="filesUpload.html" method="post"
enctype="multipart/form-data">
<p>
选择文件:<input type="file" name="files">
<p>
选择文件:<input type="file" name="files">
<p>
选择文件:<input type="file" name="files">
<p>
<input type="submit" value="提交">
</form>
</body>

controller:

  private boolean saveFile(MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
} @RequestMapping("filesUpload")
public String filesUpload(@RequestParam("files") MultipartFile[] files) {
//判断file数组不能为空并且长度大于0
if(files!=null&&files.length>0){
//循环获取file数组中得文件
for(int i = 0;i<files.length;i++){
MultipartFile file = files[i];
//保存文件
saveFile(file);
}
}
// 重定向
return "redirect:/list.html";
}

四、带参数上传
还是使用form表单进行上传,但是上传文件的时候要带上一部分的参数
例子form上传使用多个input上传多个文件并且携带参数
jsp:
其中使用了ajaxForm插件,并没有展示出来

    <form method="post" enctype="multipart/form-data" id="uploadForm"
action="${pageContext.request.contextPath}/background/worksInsert">
作品名称:<input type="text" name="name" id="name"><br>
参赛年份:<input type="text" name="year" id="year"><br>
参加竞赛:<select name="competition" id="competition">
<option value="请选择">请选择</option>
</select><br>
源文件上传:<input type="file" name="file1" id="file1"><br>
展示文件上传:<input type="file" name="file2" id="file2"><br>
附件上传:<input type="file" name="file3" id="file3"><br>
<input type="submit" value="提交"> </form>

controller:
主要是参数的书写,通过不同的value取到不同得文件,同时request.getParameter方法取到参数的值

  @RequestMapping("/worksInsert")
@ResponseBody
public MessageCarrier worksInsert(@RequestParam(value = "file1", required = false) MultipartFile file1, @RequestParam(value = "file2", required = false) MultipartFile file2, @RequestParam(value = "file3", required = false) MultipartFile file3, HttpServletRequest request) throws IOException {
MessageCarrier messageCarrier = new MessageCarrier();
if (file1 == null || request.getParameter("name") == null) {
return null;
}
// 获取源文件存储路径
String filename = request.getParameter("name");
String sworks = savePathL("works") + "/" + filename;
String vworks = savePathL("works") + "/" + filename;
String fworks = savePathL("works") + "/" + filename;
String sRealworks = System.getProperty("studentSystem.root") + sworks.substring(1, sworks.length());
String sRealvworks = System.getProperty("studentSystem.root") + vworks.substring(1, vworks.length());
String sRealfworks = System.getProperty("studentSystem.root") + fworks.substring(1, fworks.length());
DBWorks dbWorks = new DBWorks();
CompetitionWorks competitionWorks = new CompetitionWorks();
// System.out.println(request.getParameter("name"));
competitionWorks.setWorksName(request.getParameter("name")); competitionWorks.setWorksYear(request.getParameter("year"));
competitionWorks.setWorksComID(request.getParameter("competition"));
competitionWorks.setWorksIsIndex("0");
competitionWorks.setWorksNeedUpdate("0");
competitionWorks.setWorksSavePath(sworks + "/" + file1.getOriginalFilename());
// 如果有展示文件获取展示文件的存储路径
if (file2 != null && file2.getSize() != 0) {
competitionWorks.setWorksSaveViewPath(vworks + "/" + file2.getOriginalFilename());
} else {
competitionWorks.setWorksSaveViewPath("NULL");
}
// 如果有附件的话获取附件的存储路径并保存
if (file3 != null && file3.getSize() != 0) {
competitionWorks.setWorksSaveFilePath(fworks + "/" + file3.getOriginalFilename());
} else {
competitionWorks.setWorksSaveFilePath("NULL");
} //先将内容设置为NULL
competitionWorks.setWorksContent("NULL");
messageCarrier = dbWorks.worksInsert(competitionWorks);
switch (messageCarrier.getMessageContent()) {
case "OK": {
FilesUpload filesUpload = new FilesUpload();
messageCarrier = filesUpload.upload(file1, sRealworks);
if (!competitionWorks.getWorksSaveViewPath().equals("NULL")) {
messageCarrier = filesUpload.upload(file2, sRealvworks);
}
if (!competitionWorks.getWorksSaveFilePath().equals("NULL")) {
messageCarrier = filesUpload.upload(file3, sRealfworks);
} //如果上传成功则解析内容并将其录入数据库
if (messageCarrier.getMessageContent().equals("OK")) {
String path = competitionWorks.getWorksSavePath();
String filePath = System.getProperty("studentSystem.root") + path;
String fileName = path.substring(path.lastIndexOf("/") + 1);
File file = new File(filePath);
//解析文件内容
FilesToContent filesToContent = new FilesToContent();
String content = filesToContent.resolve(file);
// System.out.println(content);
competitionWorks.setWorksContent(content);
messageCarrier = dbWorks.worksUpdateName(competitionWorks);
} }
break;
default: {
return messageCarrier;
}
}
return messageCarrier;
}

本文章笔记版本地址:http://ccdd6ec5.wiz03.com/share/s/3cTmX51TMQ-b2QTact03UPg83ItAml2XO4wJ23yjLa2bEKE1

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

 
 
 
 

SpringMVC使用MultipartFile文件上传,多文件上传,带参数上传的更多相关文章

  1. netcore3.1 + vue (前后端分离) ElementUI多文件带参数上传

    vue前端代码 前端主要使用了ElementUI的el-uploda插件,除去业务代码需要注意的是使用formdata存储片上传时所需的参数 <el-upload class="upl ...

  2. 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端

    原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...

  3. 论httpclient上传带参数【commons-httpclient和apache httpclient区别】

    需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...

  4. SpringMVC 使用MultipartFile实现文件上传(转)

    http://blog.csdn.net/kouwoo/article/details/40507565 一.配置文件:SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们 ...

  5. SpringMVC 使用 MultipartFile 实现文件上传

    该代码实现了文件上传和文本字段同时传递到后台进行处理的功能. 直接贴代码,中间涉及到的实体类就不贴了,和功能没啥关系的. Controller /** * 添加活动 * * @param req * ...

  6. SpringMVC实现 MultipartFile 文件上传

    1. Maven 工程引入所需要的依赖包 2. 页面需要开放多媒体标签 3. 配置文件上传试图解析器 4. 接收图片信息,通过 IO 流写入磁盘(调用解析其中的方法即可) 如下: 1.1 引入所依赖的 ...

  7. springMVC实现 MultipartFile 多文件上传

    1.Maven引入所需的 jar 包(或自行下载) <dependency> <groupId>commons-io</groupId> <artifactI ...

  8. springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传

    总结一下 springMvc使用ajax文件上传 首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回e ...

  9. SpringMVC文件上传 Excle文件 Poi解析 验证 去重 并批量导入 MYSQL数据库

    SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库  /** * 业务需求说明: * 1 批量导入成员 并且 自主创建账号 * 2 校验数据格式 且 重复导入提示 已被 ...

随机推荐

  1. Windows获取时间函数(使用GetLocalTime,GetSystemTime,SystemTimeToTzSpecificLocalTime,GetFileTime API函数

    获取本地时间 typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; ...

  2. N 个互异数的数组的平均逆序数

    N 个互异数的数组的平均逆序数为 N(N−1)/4 1. 简单证明 对于任意的数的表 L(5,8,9,6,4),以及其反序表 Lr(4,6,9,8,5),它们各自的逆序数分别为:6 ((5, 4), ...

  3. hadoop 3.x 无法访问hdfs(50070,8088)的web界面

    1.启动hadoop.然后netstat -nltp|grep 50070,如果,没有找到进程,说明没有配置web界面的端口修改hdfs-site,xml中加上如下配置 再次启动后,netstat - ...

  4. gcc安装教程(学习Linux编程只需安装cygwin)

    gcc安装教程(windows版本) —最好的C/C++编译器,没有之一 windows下的gcc有两个版本mingw和cygwin,二选一就好 已学会C++,做工程,建议用mingw 用cygwin ...

  5. 【45.61%】【codeforces 701D】As Fast As Possible

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  6. ANDROID 中设计模式的採用--结构型模式

            结构型模式中的适配器模式.外观模式.装饰模式.代理模式都属于包装模式,都是对另外的类或对象的包装,仅仅是各自的意图不同. 适配器模式通过对另外的类或对象的包装,将其接口转换为用户期 ...

  7. Linux性能测试 uptime命令

    uptime 命令用于查看服务器运行了多长时间以及有多少个用户登录,快速获知服务器的负荷情况. 以下是 uptime 的运行实例: :: up days, min, users, load avera ...

  8. python之强大的日志模块

    1.简单的将日志打印到屏幕   import logging logging.debug('This is debug message')logging.info('This is info mess ...

  9. 淘宝平台进行数据的实时传输: TimeTunnel介绍

    在班级工作中遇到似业务场景中的实时流传输数据的访问,所以,淘宝实时数据仓库这个人做了一些研究和了解. 本文介绍的业务场景和淘宝的设计TimeTunnel工具,从淘宝数据仓库团队沟通过程中的图像文字si ...

  10. zlog 程序日志的库 交叉编译(Linux生成ARM库,观察执行步骤)

    1. zlog 是个很好的写程序日志的库,功能比较强大,上手快. 2. 下载地址:https://github.com/bmanojlovic/zlog 3. cd 到文件夹下,对 autogen.s ...