技术标签: Spring MVC
文件上传是项目开发中最常用的功能。为了实现上传文件,必须将表单的 method 设置为 POST,并将 enctype 设置为 multipart/form-data。这样,浏览器才会把用户选择的文件二进制数据发送给服务器。
设置 enctype 为 multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理涉及在服务器端解析原始的 HTTP 响应。2003年,Apache Software Foundation 发布了开源的 Commons FileUpload 组件,其很快成为了 Servlet/JSP 程序员上传文件的最佳选择。Servlet 3.0 规范已经提供了方法来处理文件上传,但这种上传需要在 Servlet 中完成。而 Spring MVC 则提供了更简单的封装。
Spring MVC 为文件上传提供了直接的支持,这种支持是用即插即用的 MultipartResolver 实现的。Spring MVC 使用 Apache Commons FileUpload 技术实现了一个 MultipartResolver 实现类:CommonsMultipartResolver。因此,Spring MVC 的文件上传还需要依赖 Apache Commons FileUpload 的组件。
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<h2>文件上传</h2>
<form:form action="upload" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>文件描述:</td>
<td><input type="text" name="description"></td>
</tr>
<tr>
<td>请选择文件:</td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form:form>
</body>
</html>
package controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@Controller
public class FileUploadController {
private final static Log logger = LogFactory.getLog(FileUploadController.class);
@RequestMapping(value = "/{formName}")
public String autoForm(@PathVariable String formName){
return formName;
}
// 上传文件会自动绑定到 MultipartFile 中
@RequestMapping(value = "/upload" , method = RequestMethod.POST)
public String upload(
HttpServletRequest request,
@RequestParam("description") String description,
@RequestParam("file") MultipartFile file
) throws Exception{
// 如果文件不为空,写入上传路径
if (!file.isEmpty()){
// 上传文件路径
String path = request.getServletContext().getRealPath("/images/");
// 上传文件名
String filename = file.getOriginalFilename();
File filepath = new File(path,filename);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file.transferTo(new File(path+File.separator+filename));
return "success";
}else {
return "error";
}
}
}
Spring MVC 会将上传文件绑定到 MultipartFile 对象中。MultipartFile 提供了获取上传文件内容、文件名等方法。通过 transferTo() 方法还可以将文件存储到硬件中,MultipartFile 对象中的常用方法如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="controller"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/content/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小上限,单位为字节(10MB) -->
<property name="maxUploadSize">
<value>10485760</value>
</property>
<!-- 请求的编码格式,必须和 jsp 的 pageEncoding 属性一致,以便正确读取表单内容,默认为 ISO-8859-1 -->
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
</beans>
http://localhost:8080/FileUploadTest/uploadForm
结果如下:
目录中文件存在,上传成功。
注: 在程序运行时,如果未上传 commons-io.jar,则浏览器会报 Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/io/IOUtils
错误。如果出现此错误,将 commons-io.jar 导入项目即可修复。
在实际的项目开发中,很多时候上传的文件会作为对象的属性被保存。Spring MVC 的处理也非常简单。
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户注册</title>
</head>
<body>
<h2>用户注册</h2>
<form:form action="register" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>请上传头像:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td><input type="submit" value="注册"></td>
</tr>
</table>
</form:form>
</body>
</html>
package domain;
import org.springframework.web.multipart.MultipartFile;
import java.io.Serializable;
public class User implements Serializable {
private String username;
// 对应上传的 file,类型为 MultipartFile ,上传文件会自动绑定到 image 属性当中。
private MultipartFile image;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
}
package controller;
import domain.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@Controller
public class FileUploadController {
private final static Log logger = LogFactory.getLog(FileUploadController.class);
@RequestMapping(value = "/{formName}")
public String autoForm(@PathVariable String formName){
return formName;
}
@RequestMapping(value = "/register")
public String register(
HttpServletRequest request,
Model model,
@ModelAttribute User user){
System.out.println(user.getUsername());
// 如果文件不为空的话,写入上传路径
if (!user.getImage().isEmpty()){
// 上传文件路径
String path = request.getServletContext().getRealPath("/images/");
System.out.println(path);
// 上传文件名
String filename = user.getImage().getOriginalFilename();
System.out.println(filename);
File filepath = new File(path,filename);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
try {
user.getImage().transferTo(new File(path+File.separator+filename));
}catch (Exception e){
e.printStackTrace();
}
// 将用户添加到 model
model.addAttribute("user",user);
//跳转到下载页面
return "userInfo";
}else {
return "error";
}
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件下载</title>
</head>
<body>
<h3>文件下载</h3>
<a href="download?filename=${requestScope.user.image.originalFilename}">
${requestScope.user.image.originalFilename }
</a>
</body>
</html>
http://localhost:8080/FileUploadTest/registerForm
结果如下:
Spring MVC 的文件下载比较简单,直接在页面给出一个超链接,该链接 href 的属性等于要下载文件的文件名,就可以实现文件下载了。
Spring MVC 提供了一个 ResponseEntity 类型,使用它可以很方便的定义返回的 HttpHeaders 和 HttpStatus。
@RequestMapping(value = "/download")
public ResponseEntity<byte[]> download(
HttpServletRequest request,
@RequestParam("filename") String filename,
Model model) throws Exception {
// 下载文件路径
String path = request.getServletContext().getRealPath("/images/");
File file = new File(path+File.separator+filename);
HttpHeaders headers = new HttpHeaders();
// 下载显示的文件名,解决中文名称乱码问题
String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
// 通知浏览器以 attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment",downloadFileName);
// application/octet-stream:二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 201 HttpStatus.CREATED
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
download 处理方法接收到页面传递的文件名 filename 后,使用 Apache Commons FileUpload 组件的 FileUtils 读取项目的 iamges 文件夹下的该文件,并将其构建成 ResponseEntity 对象返回客户端下载。
使用 ResponseEntity 对象,可以很方便地定义返回的 HttpHeaders 和 HttpStatus。上面代码中的 MadiaType,代表的是 Internet Media Type,即互联网媒体类型,也叫做 MIME 类型。在 Http 协议消息头中,使用 Content-Type 来表示具体请求中的媒体类型信息。HttpStatus 类型代表的是 Http 协议中的状态。有关 MediaType 和 HttpStatus 类的详细信息参考 Spring MVC 的 API 文档。
点击下载页面的超链接,显示文件下载:
文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态
文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境
文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn
文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker
文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机
文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk
文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入
文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。 Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。
文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动
文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计
文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;gt;Jni-&amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图
文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法