java mvc附件上传_Java笔记之SpringMVC(五):上传文件

0.说在前面

1.导入jar包commons-io-x.x.jar和commons-fileupload-x.x.jar

我这里使用的是commons-io-2.4.jar和commons-fileupload-1.4.jar

2.新建fileupload.jsp和show.jsp页面

fileupload.jsp

文件上传

上传

show.jsp

Insert title here

3.springmvc.xml配置文件上传解析器

https://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/mvc

https://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd">

4.新建FileUploadController类,其中包含初始化跳转到fileupload.jsp的方法(initFileUploadPage)和文件上传的方法(fileUpload)

packagecom.springmvc.demo.controller;importjava.io.File;importjava.io.IOException;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.multipart.MultipartFile;

@Controllerpublic classFileUploadController {

@RequestMapping("/initFileUploadPage.action")publicString initFileUploadPage(){return "fileupload";

}

@RequestMapping("/fileupload.action")publicString fileUpload(HttpServletRequest request,MultipartFile myFile){//获取上传文件的原文件名

String fileName =myFile.getOriginalFilename();

String basePath= request.getServletContext().getRealPath("/upload");

File destFile=newFile(basePath, fileName);try{

myFile.transferTo(destFile);

}catch(IllegalStateException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

request.setAttribute("fileName", fileName);return "show";

}

}

59c17f2e79cc44c7f20a0f9a50c8ad7c.png

点击上传按钮进行文件的上传和页面的跳转

5e5aa1f4e43769bb10e30fc020168f3c.png

6.说明

(1).这里上传的是图片,文件自然也是不在话下的,主要是注意文件的大小,可以在springmvc.xml中的上传文件解析器中进行文件大小的配置,这里配置的是10M;

(2).这里将图片上传到了项目部署的环境上的upload文件夹中,这个目的路径根据需要自定义;

(3).为了避免同一个文件的多次上传互相覆盖或者文件同名问题,可以将文件名进行自定义,使用UUID或者加上微秒/纳秒的时间字符串都可以;

(4).提交包含文件的表单数据时,form表单上的enctype属性值要设置为multipart/form-data;

(5).SpringMVC返回视图信息时,可以在ModelAndView中设置视图名称,也可以直接返回一个视图名称字符串,都是可以的,这里就是使用的字符串,将信息放在了request作用域中;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值