阅读 104

input上传文件获取内容(文件或目录损坏且无法读取方法)

这些天忙着刷题,又怕遗忘了spring boot, 所以抽出一点时间折腾折腾,加深点印象。

spring boot 的文件上传与 spring mvc 的文件上传基本一致,只需注意一些配置即可。

环境要求: Spring Boot v1.5.1.RELEASE + jdk1.7 + myeclipse

1).引入thymeleaf,支持页面跳转

org.springframework.boot

spring-boot-starter-thymeleaf

  • 1
  • 2
  • 3
  • 4
  • 5

2).在 src/main/resources 目录下新建 static 目录和 templates 目录。 static存放静态文件,比如 css、js、image… templates 存放静态页面。先在templates 中新建一个 uploadimg.html

uploadimg.html

–>

图片

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3).在 controller 中写两个方法,一个方法跳转到上传文件的页面,一个方法处理上传文件

//跳转到上传文件的页面

@RequestMapping(value=”/gouploadimg”, method = RequestMethod.GET)

public String goUploadImg() {

//跳转到 templates 目录下的 uploadimg.html

return “uploadimg”;

}

//处理文件上传

@RequestMapping(value=”/testuploadimg”, method = RequestMethod.POST)

public @ResponseBody String uploadImg(@RequestParam(“file”) MultipartFile file,

HttpServletRequest request) {

String contentType = file.getContentType();

String fileName = file.getOriginalFilename();

/*System.out.println(“fileName–>” + fileName);

System.out.println(“getContentType–>” + contentType);*/

String filePath = request.getSession().getServletContext().getRealPath(“imgupload/”);

try {

FileUtil.uploadFile(file.getBytes(), filePath, fileName);

} catch (Exception e) {

// TODO: handle exception

}

//返回json

return “uploadimg success”;

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

4).在上面中,我将文件上传的实现写在工具类 FileUtil 的 uploadFile 方法中

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {

File targetFile = new File(filePath);

if(!targetFile.exists()){

targetFile.mkdirs();

}

FileOutputStream out = new FileOutputStream(filePath+fileName);

out.write(file);

out.flush();

out.close();

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5).在浏览器输入 :
http://localhost:8080/gouploadimg 测试

上传文件后:

在应用的 src/main/webapp/imgupload 目录下

6).如果上传的文件大于 1M 时,上传会报错文件太大的错误,在 application.properties 中设置上传文件的参数即可

spring.http.multipart.maxFileSize=100Mb

spring.http.multipart.maxRequestSize=100Mb

文章分类
百科问答
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐