spring mvc基础之文件上传(基于html5)
来源:互联网 发布:网络诽谤罪如何取证 编辑:程序博客网 时间:2024/06/05 13:26
1.web.xml文件:
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/springmvc-config.xml</param-value></init-param> <load-on-startup>1</load-on-startup><multipart-config> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold></multipart-config> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>
2.springmvc-config.xml配置文件:
<?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:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:component-scan base-package="app11b.controller" /> <context:component-scan base-package="app11b.formatter" /><mvc:annotation-driven conversion-service="conversionService" /><mvc:resources mapping="/css/**" location="/css/" /><mvc:resources mapping="/*.html" location="/" /> <mvc:resources mapping="/image/**" location="/image/" /> <mvc:resources mapping="/file/**" location="/file/" /> <!<bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/resource/messages" /> </bean><bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="app11b.formatter.DateFormatter"> <constructor-arg type="java.lang.String" value="MM-dd-yyyy" /> </bean> </set> </property></bean><bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean></beans>
3.controller:
import java.io.File;import java.io.IOException;import javax.servlet.http.HttpServletRequest;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.validation.BindingResult;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.multipart.MultipartFile;import app11b.domain.UploadedFile;@Controllerpublic class Html5FileUploadController { private static final Log logger = LogFactory.getLog(Html5FileUploadController.class); @RequestMapping(value = "/html5") public String inputProduct() { return "Html5"; } @RequestMapping(value = "/file_upload") public void saveFile(HttpServletRequest servletRequest, @ModelAttribute UploadedFile uploadedFile, BindingResult bindingResult, Model model) { MultipartFile multipartFile = uploadedFile.getMultipartFile(); String fileName = multipartFile.getOriginalFilename(); try { File file = new File(servletRequest.getServletContext().getRealPath("/file"), fileName); multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } }}
4.验证器:ProductValidator.java
import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;import app11b.domain.Product;public class ProductValidator implements Validator { @Override public boolean supports(Class<?> klass) { return Product.class.isAssignableFrom(klass); } @Override public void validate(Object target, Errors errors) { System.out.println("============== validating product"); Product product = (Product) target; ValidationUtils.rejectIfEmpty(errors, "name", "productname.required"); Float price = product.getPrice(); if (price != null && price < 0) { errors.rejectValue("price", "price.negative"); } }}
5.domain(实体):UploadedFile.java
import java.io.Serializable;import org.springframework.web.multipart.MultipartFile;public class UploadedFile implements Serializable { private static final long serialVersionUID = 72348L; private MultipartFile multipartFile; public MultipartFile getMultipartFile() { return multipartFile; } public void setMultipartFile(MultipartFile multipartFile) { this.multipartFile = multipartFile; }}
6.view(视图):
Html5.jsp:这个提交按钮不是一个提交按钮,点击它并不会上传表单。事实上,脚本利用XMLHttpRequest对象来完成上传的
<!DOCTYPE HTML><html><head><script> //totalFileLength是保存要上传的文件总长度,totalUploaded是目前已经上传的字节数,fileCount中包含了要上传的文件数量,filesUploaded是已经上传的文件数量 var totalFileLength, totalUploaded, fileCount, filesUploaded; function debug(s) { var debug = document.getElementById('debug'); if (debug) { debug.innerHTML = debug.innerHTML + '<br/>' + s; } } function onUploadComplete(e) { totalUploaded += document.getElementById('files'). files[filesUploaded].size; filesUploaded++; debug('complete ' + filesUploaded + " of " + fileCount); debug('totalUploaded: ' + totalUploaded); if (filesUploaded < fileCount) { uploadNext(); } else { var bar = document.getElementById('bar'); bar.style.width = '100%'; bar.innerHTML = '100% complete'; alert('Finished uploading file(s)'); } } function onFileSelect(e) { var files = e.target.files; // FileList object var output = []; fileCount = files.length; totalFileLength = 0; for (var i=0; i<fileCount; i++) { var file = files[i]; output.push(file.name, ' (', file.size, ' bytes, ', file.lastModifiedDate.toLocaleDateString(), ')' ); output.push('<br/>'); debug('add ' + file.size); totalFileLength += file.size; } document.getElementById('selectedFiles').innerHTML = output.join(''); debug('totalFileLength:' + totalFileLength); } function onUploadProgress(e) { if (e.lengthComputable) { var percentComplete = parseInt( (e.loaded + totalUploaded) * 100 / totalFileLength); var bar = document.getElementById('bar'); bar.style.width = percentComplete + '%'; bar.innerHTML = percentComplete + ' % complete'; } else { debug('unable to compute'); } } function onUploadFailed(e) { alert("Error uploading file"); } function uploadNext() { var xhr = new XMLHttpRequest(); var fd = new FormData(); var file = document.getElementById('files'). files[filesUploaded]; fd.append("multipartFile", file); xhr.upload.addEventListener( "progress", onUploadProgress, false); xhr.addEventListener("load", onUploadComplete, false); xhr.addEventListener("error", onUploadFailed, false); xhr.open("POST", "file_upload"); debug('uploading ' + file.name); xhr.send(fd); } function startUpload() { totalUploaded = filesUploaded = 0; uploadNext(); } window.onload = function() { document.getElementById('files').addEventListener( 'change', onFileSelect, false); document.getElementById('uploadButton'). addEventListener('click', startUpload, false); }</script></head><body><h1>Multiple file uploads with progress bar</h1><div id='progressBar' style='height:20px;border:2px solid green'> <div id='bar' style='height:100%;background:#33dd33;width:0%'> </div></div><form> <input type="file" id="files" multiple/> <br/> <output id="selectedFiles"></output> <input id="uploadButton" type="button" value="Upload"/></form><div id='debug' style='height:100px;border:2px solid green;overflow:auto'></div></body></html>
0 0
- spring mvc基础之文件上传(基于html5)
- Spring Mvc + html5 多文件上传
- Spring MVC之文件上传
- 文件上传--基于Spring MVC框架+SmartUpload
- Spring mvc实现文件上传及html5实现上传进度条
- Spring mvc系列七之 文件上传
- Spring mvc系列七之 文件上传
- java spring mvc之文件上传
- Spring MVC之文件上传与下载
- spring mvc的文件上传之优化
- spring mvc 文件上传
- spring MVC 文件上传
- Spring MVC文件上传
- Spring MVC文件上传
- spring mvc 文件上传
- Spring mvc 文件上传
- spring mvc 文件上传
- spring mvc 上传文件
- mac配置opencv
- 家居花园设计欣赏
- JBOSS实践二:多JBOSS部署
- 数据结构实验之查找二:平衡二叉树
- 匈牙利命名法
- spring mvc基础之文件上传(基于html5)
- ACM组队经验谈
- Android--NetWorkOnMainThreadException异常解决
- MVC工作流程
- #405 Submatrix Sum
- java 单元测试教程(junit)
- C# Object 的使用
- MVC 视图 数据交互
- 我的心得