说明:
文件上传的途径
文件上传主要有两种方式:
1.使用Apache Commons FileUpload元件。
2.利用Servlet3.0及其更高版本的内置支持。
客户端编程
1.为了上传文件,必须将HTML表格的enctype属性值设为multipart/form-data,像下面这样:
2.在HTML5之前,如果要想上传多个文件,必须使用多个文件input元素。但是,在HTML5中,通过在input元素中引入多个multiple属性,使得多个文件的上传变得更加简单,下面均可使一个上传框支持多个文件上传。
MultipartFile接口
在SpringMVC中处理已经上传的文件十分简单,上传到SpringMVC应用程序中的文件会被包在一个MultipartFile对象中,你唯一要做的事情就是用类型为MultipartFile的属性编写一个Domain类。就像下面这样:
package domain;
import org.springframework.web.multipart.MultipartFile;
import java.io.Serializable;
import java.util.List;
public class Product implements Serializable {
//实现了这个接口,可以安全的将数据保存到HttpSession中
private long id;
private String name;
private String description;
private String price;
//在Domain类中加入MultipartFile类型的属性,用来保存上传的文件
private List images;
public List getImages() {
return images;
}
public void setImages(List images) {
this.images = images;
}
......多个get和set方法。
MultipartFile接口提供了以下方法:
| Modifier and Type | Method and Description |
|---|---|
| byte[] | getBytes()Return the contents of the file as an array of bytes. |
| String | getContentType()Return the content type of the file. |
| InputStream | getInputStream()Return an InputStream to read the contents of the file from. |
| String | getName()Return the name of the parameter in the multipart form. |
| String | getOriginalFilename()Return the original filename in the client's filesystem. |
| long | getSize()Return the size of the file in bytes. |
| boolean | isEmpty()Return whether the uploaded file is empty, that is, either no file hasbeen chosen in the multipart form or the chosen file has no content. |
| void | transferTo(File dest)Transfer the received file to the given destination file. |
实例:用CommonsFileUpLoad上传文件
导入Jar包及配置环境变量
编写视图
代码:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %>Add Product Form
说明:
progressBar div用于展示上传进度,debug div用于显示调试信息。
执行脚本时,第一件事就是为4个变量分配空间:totalFileLength,totalUploaded,fileCount,filesUploaded;
- totalFileLength:主要用于保存上传文件的总长度。
- totalUploaded:指示目前已经上传的字节数。
- fileCount:包含了要上传的文件数量。
- fileUploaded:指示了已经上传的文件数量。
以上所述是小编给大家介绍的SpringMVC文件上传功能实例解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



