SpringMVC文件上传(二)指定文件

在上面的一节中,我们查看运行的结果,即然在一个zip格式的文件,这显然不是我们所想要的,所以这一节,我们主要处理就是,要用户必须上传图片,而且上传的文件不能太大,如里不满足的话,那么页面将会报错,报错信息要以友好地形式提示。

1.上传是图片文件

     我们修改pictureUploadController的类,修改的目的是文件 必须是图片的。下面是笔者修改后的代码。

package masterSpringMvc.profile;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.*;
@Controller
public class PictureUploadController {
public static final Resource PICTURES_DIR = new
FileSystemResource("./pictures");
@RequestMapping("upload")
public String uploadPage() {
return "profile/uploadPage";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String onUpload(MultipartFile file, RedirectAttributes
redirectAttrs) throws IOException {
if (file.isEmpty() || !isImage(file)) {
redirectAttrs.addFlashAttribute("error", "Incorrect file.
Please upload a picture.");
return "redirect:/upload";
}
copyFileToPictures(file);
return "profile/uploadPage";
}
private Resource copyFileToPictures(MultipartFile file) throws
IOException {
String fileExtension = getFileExtension(file.
getOriginalFilename());
File tempFile = File.createTempFile("pic", fileExtension,
PICTURES_DIR.getFile());
try (InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
return new FileSystemResource(tempFile);
}
private boolean isImage(MultipartFile file) {
return file.getContentType().startsWith("image");
}

2.视图层修改

我们首先还是在两份国际化文件中添加下面的字段,对于法语的文件 ,读者自己翻译添加。

upload.io.exception=An error occurred while uploading the file. Please try again.
upload.file.too.big=Your file is too big.

之后,我们在uploadPage中添加下面的代码,这个作用就是当文件上传不是图片时风们要友好地提示。

<div class="col s12 center red-text" th:text="${error}"
th:if="${error}">
Error during upload
</div>

3.总结

这里笔者已经对上传文件做了处理,要求就是上传的文件必须是图片,如日不是图片,那么将会提示下图的信息。可是还有问题,笔者有之前说过了要对文件的大小作判断,如果大小超出了范围,我们也要友好提示,可是这一章节里,我们并没有实现。不要着急,我们下一节将会讲解。


源码下载:git@github.com:owenwilliam/masterSpringMVC.git





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值