SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件

时间:2023-03-09 05:50:05
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
@Email
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