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 ...
随机推荐
- 2 WPF之XMAL----XMAL概览
转载:http://blog.csdn.net/fwj380891124/article/details/8085458 微软为了把开发模式从网络开发移植到桌面开发和富媒体网络程序的开发上,微软创造了 ...
- JD(转载)
时间:2012-9-11 地点:川大 我只能说第一家公司,不是一般的火爆.不得不吐槽一下: 京东宣讲完全没有计划,只看到个下午两点半宣讲,结果跑过去,下午两点是宣讲管培的.在川大外的德克士呆了一下午. ...
- 总结&记录
一.Git(linux命令) 1.tar 压缩/解压 -c 建立一个压缩文件(create) -x 解压一个压缩文件 -t 查看tarfile中文件 -z 是否具有gzip的属性?是否需要用gzip ...
- Oracle——事务(Transaction)
事务: 事务是指作为单个逻辑工作单元执行的一组相关操作. 这些操作要求全部完成或者全部不完成. 使用事务的原因:保证数据的安全有效. 事务的四个特点:(ACID) 1.原子性(Atomic):事务中所 ...
- JSTL 入门
JSTL--JSP Standard Tag Library--JSP标准标签函式库 当前版本 1.2.5 JSP 标准标签库(JSTL) JSP标准标签库(JSTL)是一个J ...
- Codevs 2611 观光旅游(floyed最小环)
2611 观光旅游 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description 某旅游区里面有N个景点.两个景点之间可能直接有道路相连,用 ...
- [Guava官方文档翻译] 2.使用和避免使用null (Using And Avoiding Null Explained)
本文地址:http://www.cnblogs.com/hamhog/p/3536647.html "null很恶心." -Doug Lea "这是一个令我追悔莫及的错误 ...
- WPF异步调用WCF服务
wpf调用wcf时,第一次访问总耗时到达几秒,影响界面的用户体验,因此在wpf加载界面和加载数据时采用异步加载,即异步访问wcf服务, 由于是否采用异步加载和服务端无关,仅仅由客户端自己根据需要来选择 ...
- 网页中"IE限制网页访问脚本或ActiveX控件"的提示问题的解决方法
以前从来没有注意过"IE限制网页访问脚本或ActiveX控件"的提示问题,对于这个小细节问题,虽然感觉很别扭,但一直没考虑解决方法,今天才发现该问题可以轻松解决,以下做个小小记录. ...
- JavaScript 中的内存泄漏
JavaScript 中的内存泄漏 JavaScript 是一种垃圾收集式语言,这就是说,内存是根据对象的创建分配给该对象的,并会在没有对该对象的引用时由浏览器收回.JavaScript 的垃圾收集机 ...