使用springmvc实现文件上传
该配置在javaweb上传文件篇中的基础上进行配置:https://www.cnblogs.com/flypig666/p/11745182.html
1、配置文件解析器,在springmvc.xml中进行配置
<!-- 配置文件解析器,id必须为multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760" /> </bean>
2、编写jsp
<h3>springmvc:文件上传</h3> <form action="file/upload2" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="upload2" /><br/> <input type="submit" value="上传" /> </form>
3、编写controller
/** * SpringMVC文件上传 * @param request * @return * @throws Exception * MultipartFile upload2: upload2为提交文件按钮的name值,表示文件上传项 */ @RequestMapping("/upload2") public String fileupload1(HttpServletRequest request, MultipartFile upload2) throws Exception { System.out.println("springmvc文件上传"); // 使用fileupload组件完成组件上传 // 上传的位置 // request.getSession().getServletContext():拿到最大的域对象,getRealPath():拿到某路径下的绝对路径 String path = request.getSession().getServletContext().getRealPath("/uploads/"); // 判断该路径是否存在 File file = new File(path); if (!file.exists()){ // 创建文件夹 file.mkdirs(); } // springmvc不需要自己解析request // 获取上传文件名 String filename = upload2.getOriginalFilename(); // 把文件的名称设置为唯一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid + "_" + filename; // 完成文件上传 upload2.transferTo(new File(file,filename)); return "success"; }
相关推荐
dlutbob 2020-06-17
MicroBoy 2020-06-05
横云断岭 2020-03-08
haidaoxianzi 2020-03-04
也许不会看见 2020-02-21
whbing 2020-02-14
whbing 2019-12-14
zlllxl00 2017-08-20
Richardxx 2020-01-04
Richardxx 2019-12-24
方志朋 2019-12-08
凯哥Java 2019-11-03
cloudspring 2014-08-14
RogerCoderLife 2019-07-01
MayMatrix 2018-08-06
Sweetdream 2017-08-20
白净垃圾桶 2014-08-22
cloudspring 2014-08-19