SpringMVC详解第三天

目录

一.文件上传

1.文件上传的原理

2.文件上传到本地服务器

(1) 在pom.xml文件中导入文件上传的依赖

(2) 创建一个文件上传页面

(3) 在springmvc中配置文件上传解析器  

(4) 创建upload01接口方法  

二.文件回显 

1.将文件传入服务器的文件回显到网页上

(1)页面的布局 

(2)后台的接口  


一.文件上传

1.文件上传的原理

2.文件上传到本地服务器

(1) 在pom.xml文件中导入文件上传的依赖

<!--文件上传的依赖-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

(2) 创建一个文件上传页面


  method: 提交方式 文件上传必须为post提交。
  enctype:默认application/x-www-form-urlencoded 表示提交表单数据
  multipart/form-data:可以包含文件数据

  input的类型必须为file类型,而且必须有name属性
 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--
      method: 提交方式 文件上传必须为post提交。
      enctype:默认application/x-www-form-urlencoded 表示提交表单数据
              multipart/form-data:可以包含文件数据

      input的类型必须为file类型,而且必须有name属性
   --%>
    <form method="post" action="upload01" enctype="multipart/form-data">
        <input type="file" name="myfile" />
        <input type="submit" name="提交" />
    </form>
</body>
</html>

(3) 在springmvc中配置文件上传解析器  

<!--    配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <!--这里的value单位为字节10M*1024K*1024-->
        <property name="maxUploadSize" value="10485760"/>
    </bean>

(4) 创建upload01接口方法  

String filename= UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename()

相当于:

//给传入本地服务器的照片设置一个名字
UUID uuid = UUID.randomUUID();
//将自动生成的名字转为toString格式
String s = uuid.toString();
//将自动生成的名字中的-替换为空,并拼接文件原先的名字和后缀,生成一个新的名字
String replace = s.replace("-", "")+myfile.getOriginalFilename();
@Controller
public class HelloController02 {

    @RequestMapping(value = "upload03")
    public String upload03(HttpServletRequest request, MultipartFile myfile) throws Exception{
        String path = request.getSession().getServletContext().getRealPath("upload");
        //System.out.println(path);
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        //给传入本地服务器的照片设置一个名字
        UUID uuid = UUID.randomUUID();
        //System.out.println(uuid);
        //将自动生成的名字转为toString格式
        String s = uuid.toString();
        //System.out.println(s);
        //将自动生成的名字中的-替换为空,并拼接文件原先的名字和后缀,生成一个新的名字
        String replace = s.replace("-", "")+myfile.getOriginalFilename();
        //System.out.println(replace);
        //传入文件本地服务器存储路径并使用"/"拼接已经生成好的新名字
        File target = new File(path + "/" + replace);
        myfile.transferTo(target);//将通过网页传入到服务器的文件myfile转移到目标目录下并将名字更改为我们随机生成好的拼接名字

//        String replace1 = UUID.randomUUID().toString().replace("-", "")+myfile.getOriginalFilename();
//        File file1 = new File(path + "/" + replace1);
//        myfile.transferTo(file1);
        return "";
    }

}

二.文件回显 

1.将文件传入服务器的文件回显到网页上

elementui+vue+axios完成文件上传

(1)页面的布局 

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <!--引入vue得js文件 这个必须在element之前引入-->
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <!--element得js文件-->
    <script type="text/javascript" src="js/index.js"></script>
</head>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
<body>
    <div id="hz">
        <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/springmvc03lx01/upload02"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</body>
</html>
<script>
    var app = new Vue({
        el:"#hz",
        data:{
            imageUrl:'',

        },
        methods:{
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG= file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            }
        }
    })
</script>

 

(2)后台的接口  

@RequestMapping("upload02")
    @ResponseBody
    public CommentRestult upload02(HttpServletRequest request, MultipartFile file){
        try{
            String path = request.getSession().getServletContext().getRealPath("upload");
            File file1 = new File(path);
            if (!file1.exists()){
                file1.mkdirs();
            }
            String replace = UUID.randomUUID().toString().replace("-", "")+file.getOriginalFilename();
            File file2 = new File(path + "/" + replace);
            file.transferTo(file2);
            CommentRestult restult = new CommentRestult(2000,"成功",file2);
            return restult;
        }catch (Exception e){
            e.printStackTrace();
        }
        CommentRestult restult = new CommentRestult(5000, "失败", null);
        return restult;

    }

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值