关于文件上传

2023-11-12

目录

1.文件上传的原理

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

2.1 添加上传的依赖

2.2 创建一个页面

2.3 在springmvc中配置文件上传解析器

2.4 创建upload01接口方法

3.elementui+vue+axios完成文件上传

3.1 页面的布局引用elementui

3.2 后台的接口


1.文件上传的原理

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

2.1 添加上传的依赖

<dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.4</version>
   </dependency>

2.2 创建一个页面

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

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

<form method="post" enctype="multipart/form-data" action="fileUp">
        <input type="file" value="上传图片" name="myfile">
        <input type="submit" value="提交">
    </form>

2.3 在springmvc中配置文件上传解析器

     id的名称必须叫multipartResolver


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

2.4 创建upload01接口方法

  //注意:MultipartFile 参数名必须和<input type="file" name="myfile"/>中name属性相同
    @RequestMapping("/upload01")
    public String upload01(MultipartFile myfile, HttpServletRequest request) throws Exception{

        //(1)得到本地服务目录的地址
        String path = request.getSession().getServletContext().getRealPath("upload");
        //(2)判断该对应目录路径所对应的目录是否存在
        File file=new File(path);
        if(!file.exists()){
             file.mkdirs();
        }
        //(3)//把myfile保存到本地服务中某个文件夹下。UUID.randomUUID()生成随机字码
        //myfile.getOriginalFilename()获取所上传文件的原始文件名,因为想要后缀名
    String filename= UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        //文件路径
        File target=new File(path+"/"+filename);
        myfile.transferTo(target); //把myfile转移到目标目录下
        return "";
    }

3.elementui+vue+axios完成文件上传

3.1 页面的布局引用elementui

此处注意要引入样式

<head>
    <title>登录页面2</title>
    <link type="text/css" rel="stylesheet"  href="css/index.css">
    <script type="text/javascript" src="js/qs.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <script type="text/javascript" src="js/vue.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <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>

</head>
<body>
<div id="con">
    <el-upload
            class="avatar-uploader"
        //注意此处的跳转网页
            action="fileUp01"
            :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>
<script>
    var app=new Vue({
        el:"#con",
        data:{
            imageUrl: ''
        },
        methods: {
             //上传成功后触发的方法
            handleAvatarSuccess(res, file) {
            //此处进行数据修改
                this.imageUrl =res.date;
            },
        //上传前触发的方法
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

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

3.2 后台的接口

    @RequestMapping("fileUp01")
    @ResponseBody
    public CommonResult test02(MultipartFile file, HttpSession session){
        try{
//1.获取上传到服务器的文件夹路径
            String path = session.getServletContext().getRealPath("path1");
            File file = new File(path1);//此路径下创建文件对象
            if(!file.exists()){
                file.mkdirs();
            }
            String filename=UUID.randomUUID().toString().replace("-","")
                    + file.getOriginalFilename();//图片名
            File file1 = new File(path + "/" + filename);
            file.transferTo(file1);
            CommonResult success = CommonResult.success("http://localhost:8080/keqianceSpring/path1/"+filename);
            return success;
        } catch (IOException e) {
            e.printStackTrace();
        }
        CommonResult error = CommonResult.error(500);
        return error;

        读取照片和写入照片,除了上述使用的file.transferTo(file1)方法,还可以使用IO流来做,举例:

@Controller
public class UploadFile02 {
    @RequestMapping("/load02")
    @ResponseBody
    public CommonResult test01(MultipartFile file, HttpSession httpSession) throws IOException {
        String path = httpSession.getServletContext().getRealPath("path");
        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdirs();
        }
        String pName=UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
        File file2 = new File(file1, pName);
        if(!file2.exists()){
            file2.createNewFile();
        }
        try(InputStream inputStream=file.getInputStream();
            OutputStream outputStream=new FileOutputStream(file2)){
            byte[] b=new byte[1024];
            int len=0;
            while((len=inputStream.read(b))!=-1){
                outputStream.write(b,0,len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            return CommonResult.success("http://localhost:8080/keqianceSpring/path/"+pName);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.error("上传失败");
        }
    }
}

CommonResult

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult {
    private final static int success=200;
    private final static int error=500;
    private final static int not_fount=404;
    private  int code;
    private  String msg;
    //注意此处的date,后续要是不能打印注意看此处
    private Object date;

    public static CommonResult success(Object date){
        return new CommonResult(CommonResult.success,"success",date);
    }
    public static CommonResult error(Object date){
        return new CommonResult(CommonResult.error,"未知错误,请联系管理员",date);
    }
    public static CommonResult notFount(){
        return new CommonResult(CommonResult.not_fount,"资源不存在",null);
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于文件上传 的相关文章

随机推荐

  • python面向对象的方法计算圆的周长和面积

    class yuan def init self r self r r print 圆的半径为 self r def get circle self print 圆的周长为 2 3 14 self r def get area self p
  • 【爬虫练习】爬取知乎\百度热搜榜

    利用requests模块和re正则爬取知乎 百度热搜榜问题 并将数据保存到EXCEL中 一 发送get请求 import requests import re import datetime import openpyxl import o
  • VS Code(html)基础标签及代码

    浏览器F12 打开检查源代码 基础标签 头文件 包含元数据 如文档的标题 字符集 样式表链接等 包裹整个HTML文档 内容 网页标题 定义文档的标题 显示在浏览器的标题栏或标签页 网页图标 包含网页的所有内容 如文本 图像 音频 视频等 注
  • 如何开启mysql计划事件

    首先在sql中查询计划事件的状态 SHOW VARIABLES LIKE event scheduler 如果返回的是off表示当前是关闭状态 如果是on当前已经开启了计划任务 在mysql程序的目录下找到my ini文件 添加一个项 ev
  • vue修改网站名称和图标

    在项目中找到public文件夹下面的index html 修改如下图
  • oh-my-zsh自定义配置

    oh my zsh主题配置 默认的zsh主题robbyrussell已经很棒了 简洁高效 能很好的显示git的相关信息 比如branch信息 修改 删除 添加等操作 但是多用户的话就不能很好的展示 我们可以通过修改robbyrussell的
  • No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=armv7 armv7s)

    当运行工程出现 错误代码 No architectures to compile for ONLY ACTIVE ARCH YES active arch x86 64 VALID ARCHS armv7 armv7s 时 按照上图 设置选
  • idea中 启动错误: 找不到或无法加载主类 解决办法

    说真的 用了idea后感觉很强大 但是有时候也会有很多坑 最近就遇到一个问题 启动错误 找不到或无法加载主类 刚新建一个util类 写了一个简单的main方法 然后输出一句话 就是这么简单 然后main 方法run的时候报 错误 找不到或无
  • jpg、png、jpeg区别与压缩等知识总结 —— 性能优化篇

    jpeg jpeg是一个国家专家小组 同事也是一种算法名称 而用JPEG算法压缩出来的静态图片文件称为JPEG文件 扩展名通常为 jpg jpe jpeg JPEG文件大体上可以分成两个部分 标记码 Tag 和压缩数据 标记码由两个字节构成
  • 我是如何设计一个包办所有对企政策的城市平台

    它是容纳了一个城市所有政府对企政策的平台 它的非正式代号是 城市主站 它的定位是 只要这个平台部署在某 入口 1 和子站入口 2 恰好对应了 路径的上一层 于是我用最少的元素实现了导航的逻辑完备 一个政策能看和能办是两回事 政策任何时候都可
  • SQL 课后作业答案 练习2 练习6

    Exercise2 1 Find the name and salary of employees in Luton SELECT ename sal FROM emp e dept2020290223 d WHERE loc Luton
  • vue-admin 完全隐藏掉左侧菜单栏

    在 src styles sidebar scss文件中修改第一个 hideSidebar hideSidebar sidebar container sidebar container el menu width 36px importa
  • DBeaver改变字体

    dbeaver的sql编辑区字体小 费眼 想改变字体 在设置中没有改变字体的设置 折腾好半天 发现另一种曲线救国的方式
  • 一周Hard (2021.11.29-2021.12.05)

    862 和至少为 K 的最短子数组 先从朴素的思想去考 枚举当前的前缀和 k k k 那么我们需要找到当前位置之前的满足差大于等于 k k k的最大位置 i
  • 【翻译】什么是 "政策即守则"?

    身份很容易 毕竟 每个人都有一个 认证 可能就更不复杂了 任何使用智能手机的人每天都要认证几十次才能使用它 这甚至还没有涉及银行 工作或社交媒体所需的远程服务 也许正是这种明显的简单性吸引了我在大约五六年前进入身份系统的世界 在这之前的几年
  • python 可视化_提升你的Python可视化编程技能,一文学会图表添加参考线和区域...

    前两次呢 已经和大家讨论了关于Python数据可视化的经典库matplotlib相关的东东 已经介绍了plot scatter xlim ylim xlabel ylabel 和grid 这几个函数哦 下面呢 咱们继续前两节的内容 继续和大
  • linux————pxe网络批量装机

    目录 一 概述 什么是pxe pxe组件 二 搭建交互式pxe装机 一 配置基础环境 二 配置vsftpd 三 配置tftp 四 准备pxelinx 0文件 引导文件 内核文件 一 准备pxelinux 0 二 准备引导文件 内核文件 五
  • 让 AI 真正读懂人类语言,5分钟搞懂 word embedding 技术

    大家好啊 我是董董灿 在学习自然语言处理 NLP Natural Language Processing 时 最先遇到的一个概念 可能就是词嵌入 word embedding 了 词嵌入 是让AI真正理解人类自然语言的技术 看完本文再回过头
  • python+requests接口自动化测试

    原来的web页面功能测试转变成接口测试 之前大多都是手工进行 利用postman和jmeter进行的接口测试 后来 组内有人讲原先web自动化的测试框架移驾成接口的自动化框架 使用的是java语言 但对于一个学java 却在学python的
  • 关于文件上传

    目录 1 文件上传的原理 2 文件上传到本地服务器 2 1 添加上传的依赖 2 2 创建一个页面 2 3 在springmvc中配置文件上传解析器 2 4 创建upload01接口方法 3 elementui vue axios完成文件上传