spring MVC学习笔记(五)文件上传

配置虚拟目录

配置虚拟路径
配置好虚拟路径后,我们可以通过虚拟路径来访问文件

编写Controller

 @RequestMapping("/editItemSubmit")
    public String editItemSubmit(MultipartFile pictureFile, Model model)throws Exception {

        //原始文件名称
        String pictureFile_name = pictureFile.getOriginalFilename();
        //新文件名称
        String newFileName = UUID.randomUUID().toString() + pictureFile_name.substring(pictureFile_name.lastIndexOf("."));

        //上传图片
        File uploadPic = new java.io.File("E:/workspace/ideapj/learnspringmvc/upload/temp/" + newFileName);

        if (!uploadPic.exists()) {
            uploadPic.mkdirs();
        }
        //向磁盘写文件
        pictureFile.transferTo(uploadPic);
        model.addAttribute("tp","/pic/temp"+newFileName);
        return "upload";
    }

编写jsp页面

<%--
  Created by IntelliJ IDEA.
  User: 黄维
  Date: 2018/8/9
  Time: 15:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form id="itemForm"
      action="${pageContext.request.contextPath }/editItemSubmit.do"
      method="post"  enctype="multipart/form-data">

    <img src="${tp}">
    <input type="file" name="pictureFile">
    <input type="submit" value="上传">
</form>
</body>
</html>

此时需要指定form表单的属性enctype为multipart/form-data

配置文件上传

    <!-- 文件上传 -->

    <bean id="multipartResolver"

          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <property name="maxUploadSize" value="209715200" />

        <property name="defaultEncoding" value="UTF-8" />

        <property name="resolveLazily" value="true" />

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值