SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件
一、用 MultipartFile
1.在html中设置<form enctype="multipart/form-data">及<input type="file">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spitter</title>
<link rel="stylesheet" type="text/css"
th:href="@{/resources/style.css}"></link>
</head>
<body>
<div id="header" th:include="page :: header"></div> <div id="content">
<h1>Register</h1> <form method="POST" th:object="${spitter}" enctype="multipart/form-data">
<div class="errors" th:if="${#fields.hasErrors('*')}">
<ul>
<li th:each="err : ${#fields.errors('*')}"
th:text="${err}">Input is incorrect</li>
</ul>
</div>
<label th:class="${#fields.hasErrors('firstName')}? 'error'">First Name</label>:
<input type="text" th:field="*{firstName}"
th:class="${#fields.hasErrors('firstName')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('lastName')}? 'error'">Last Name</label>:
<input type="text" th:field="*{lastName}"
th:class="${#fields.hasErrors('lastName')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('email')}? 'error'">Email</label>:
<input type="text" th:field="*{email}"
th:class="${#fields.hasErrors('email')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('username')}? 'error'">Username</label>:
<input type="text" th:field="*{username}"
th:class="${#fields.hasErrors('username')}? 'error'" /><br/> <label th:class="${#fields.hasErrors('password')}? 'error'">Password</label>:
<input type="password" th:field="*{password}"
th:class="${#fields.hasErrors('password')}? 'error'" /><br/> <label>Profile Picture</label>:
<input type="file"
name="profilePicture"
accept="image/jpeg,image/png,image/gif" /><br/> <input type="submit" value="Register" />
</form>
</div>
<div id="footer" th:include="page :: copy"></div>
</body>
</html>
2.在实体bean中对应字段的类型设置为org.springframework.web.multipart.MultipartFile,以支持自动装配
package spittr.web; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email;
import org.springframework.web.multipart.MultipartFile; import spittr.Spitter; public class SpitterForm { @NotNull
@Size(min=5, max=16, message="{username.size}")
private String username; @NotNull
@Size(min=5, max=25, message="{password.size}")
private String password; @NotNull
@Size(min=2, max=30, message="{firstName.size}")
private String firstName; @NotNull
@Size(min=2, max=30, message="{lastName.size}")
private String lastName; @NotNull
private String email; private MultipartFile profilePicture;
3.在handler中保存
(1)
@RequestMapping(value="/register", method=POST)
public String processRegistration(
@Valid SpitterForm spitterForm,
Errors errors) throws IllegalStateException, IOException { if (errors.hasErrors()) {
return "registerForm";
}
Spitter spitter = spitterForm.toSpitter();
spitterRepository.save(spitter);
MultipartFile profilePicture = spitterForm.getProfilePicture();
profilePicture.transferTo(new File(spitter.getUsername() + ".jpg"));
return "redirect:/spitter/" + spitter.getUsername();
}
(2)也可以用RequestPart数组来接收图片数组
@RequestMapping(value = "/register", method = POST)
public String processRegistration(
@RequestPart("profilePicture") byte[] profilePicture,
@Valid Spitter spitter,
Errors errors) {
...
}
If the user submits the form without selecting a file, then the array will be empty (but not null ).
(3)用MultipartFile类型的函数参数来接收图片
@RequestMapping(method = RequestMethod.POST)
public String processUpload(@RequestPart("file") MultipartFile profilePicture) {
profilePicture.transferTo(new File("/data/spittr/" + profilePicture.getOriginalFilename()));
}
(4)把图片保存到Amazon S3
private void saveImage(MultipartFile image)
throws ImageUploadException {
try {
AWSCredentials awsCredentials = new AWSCredentials(s3AccessKey, s2SecretKey);
S3Service s3 = new RestS3Service(awsCredentials);
S3Bucket bucket = s3.getBucket("spittrImages");
S3Object imageObject = new S3Object(image.getOriginalFilename());
imageObject.setDataInputStream(image.getInputStream());
imageObject.setContentLength(image.getSize());
imageObject.setContentType(image.getContentType());
AccessControlList acl = new AccessControlList();
acl.setOwner(bucket.getOwner());
acl.grantPermission(GroupGrantee.ALL_USERS, Permission.PERMISSION_READ);
imageObject.setAcl(acl);
s3.putObject(bucket, imageObject);
} catch (Exception e) {
throw new ImageUploadException("Unable to save image", e);
}
}
The first thing that saveImage() does is set up Amazon Web Service ( AWS ) credentials. For this, you’ll need an S3 access key and an S3 secret access key. These will be given to you by Amazon when you sign up for S3 service. They’re provided to SpitterController via value injection.
With the AWS credentials in hand, saveImage() creates an instance of JetS3t’s RestS3Service , through which it operates on the S3 filesystem. It gets a reference to the spitterImages bucket, creates an S3Object to contain the image, and then fills that S3Object with image data.
Just before calling the putObject() method to write the image data to S3, saveImage() sets the permissions on the S3Object to allow all users to view it. This is important—without it, the images wouldn’t be visible to your application’s users.Finally, if anything goes wrong, an ImageUploadException will be thrown.
4.在配置文件中设置好处理上传的bean和约束
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("/tmp", 2097152, 4194304, 0));
}
二、用 javax.servlet.http.Part
1.
@RequestMapping(value = "/register", method = POST)
public String processRegistration(
@RequestPart("profilePicture") Part profilePicture,
@Valid Spitter spitter,
Errors errors) {
...
}
In many cases, the Part methods are named exactly the same as the MultipartFile methods. A few have similar but different names; getSubmittedFileName() , for example, corresponds to getOriginalFilename() . Likewise, write() corresponds to transferTo() , making it possible to write the uploaded file like this:
profilePicture.write("/data/spittr/" + profilePicture.getOriginalFilename());
It’s worth noting that if you write your controller handler methods to accept file uploads via a Part parameter, then you don’t need to configure the StandardServlet-MultipartResolver bean. StandardServletMultipartResolver is required only
when you’re working with MultipartFile
SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件的更多相关文章
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver
一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice
No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)
一.redirect为什么会丢数据? when a handler method completes, any model data specified in the method is copied ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynamic、WebApplicationInitializer)
一. 1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherSer ...
- SPRING IN ACTION 第4版笔记-第五章Building Spring web applications-001-SpringMVC介绍
一. 二.用Java文件配置web application 1. package spittr.config; import org.springframework.web.servlet.suppo ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)
一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error
一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)
一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...
随机推荐
- JobControl管理多job依赖完整示例
处理 复杂的要求的时候,有时一个mapreduce程序是完成不了的,往往需要多个mapreduce程序,这个时候就要牵扯到各个任务之间的依赖关系,所谓 依赖就是一个MR Job 的处理结果是另外的MR ...
- SQL Server调优系列进阶篇 - 如何重建数据库索引
随着数据的数据量的急剧增加,数据库的性能也会明显的有些缓慢这个时候你可以考虑下重建索引或是重新组织索引了. DBCC SHOWCONTIG('表名') 可以查看当前表的索引碎情况. 重建索引 方法一: ...
- mysqld-nt: Out of memory (Needed 1677720 bytes)解决方法
http://www.jb51.net/article/58726.htm 今天发现网站有点慢,发现mysql日志中提示mysqld-nt: Out of memory (Needed 1677720 ...
- Cisco交换机中的flash,Rom,RAM,nvram的区别
Flash内存,也叫闪存,是路由器当中常用的一种内存类型.它是可读写的存储器,在系统重新启动或关机之后仍能保存数据.Flash中存放着当前使用中的IOS(路由器操作系统). 只读内存(ROM)在Cis ...
- swift-计算器(斯坦福公开课)
看了斯坦福老头的课,真心觉得,我的中文怎么也变的这么垃圾了.是关于iOS8的课程,用swift写的,一个计算器应用的制作,看看人家的课,再看看咱们学校的课(不过垃圾学校,纯粹觉得大学浪费了),废话啊, ...
- Objective-C 学习笔记(Day 3,下)
------------------------------------------- 封装概念及其原理 一个Gun类的例子来详细说明这一环节: #import <Foundation/Foun ...
- 学习redis-安装和基本一些命令
redis安装 linux下环境安装redis,我这里下载的是3.0.0版本(目前最新版3.2.0). $ wget http://download.redis.io/releases/redis-3 ...
- RabbitMQ远程访问配置
1 首先创建一个新的账户 并给上Administrator标签 2然后给这个新账户添加虚拟主机访问权限 3在windows 下的 rabbitmq安装文件下的etc文件下的配置文件添加以下 [ ...
- leetcode Largest Rectangle in Histogram 单调栈
作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052343.html 题目链接 leetcode Largest Rectangle in ...
- Ambry: LinkedIn’s Scalable Geo-Distributed Object Store
https://github.com/linkedin/ambry http://www.open-open.com/lib/view/open1464828607502.html