• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

文件上传

武飞扬头像
青柠果
帮助1

目录

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 添加上传的依赖

  1.  
    <dependency>
  2.  
    <groupId>commons-fileupload</groupId>
  3.  
    <artifactId>commons-fileupload</artifactId>
  4.  
    <version>1.4</version>
  5.  
    </dependency>

2.2 创建一个页面

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

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

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

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

     id的名称必须叫multipartResolver

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

2.4 创建upload01接口方法

  1.  
    //注意:MultipartFile 参数名必须和<input type="file" name="myfile"/>中name属性相同
  2.  
    @RequestMapping("/upload01")
  3.  
    public String upload01(MultipartFile myfile, HttpServletRequest request) throws Exception{
  4.  
     
  5.  
    //(1)得到本地服务目录的地址
  6.  
    String path = request.getSession().getServletContext().getRealPath("upload");
  7.  
    //(2)判断该对应目录路径所对应的目录是否存在
  8.  
    File file=new File(path);
  9.  
    if(!file.exists()){
  10.  
    file.mkdirs();
  11.  
    }
  12.  
    //(3)//把myfile保存到本地服务中某个文件夹下。UUID.randomUUID()生成随机字码
  13.  
    //myfile.getOriginalFilename()获取所上传文件的原始文件名,因为想要后缀名
  14.  
    String filename= UUID.randomUUID().toString().replace("-","") myfile.getOriginalFilename();
  15.  
    //文件路径
  16.  
    File target=new File(path "/" filename);
  17.  
    myfile.transferTo(target); //把myfile转移到目标目录下
  18.  
    return "";
  19.  
    }
学新通

3.elementui vue axios完成文件上传

3.1 页面的布局引用elementui

此处注意要引入样式

  1.  
    <head>
  2.  
    <title>登录页面2</title>
  3.  
    <link type="text/css" rel="stylesheet" href="css/index.css">
  4.  
    <script type="text/javascript" src="js/qs.min.js"></script>
  5.  
    <script type="text/javascript" src="js/axios.min.js"></script>
  6.  
    <script type="text/javascript" src="js/vue.js"></script>
  7.  
    <script type="text/javascript" src="js/index.js"></script>
  8.  
    <style>
  9.  
    .avatar-uploader .el-upload {
  10.  
    border: 1px dashed #d9d9d9;
  11.  
    border-radius: 6px;
  12.  
    cursor: pointer;
  13.  
    position: relative;
  14.  
    overflow: hidden;
  15.  
    }
  16.  
    .avatar-uploader .el-upload:hover {
  17.  
    border-color: #409EFF;
  18.  
    }
  19.  
    .avatar-uploader-icon {
  20.  
    font-size: 28px;
  21.  
    color: #8c939d;
  22.  
    width: 178px;
  23.  
    height: 178px;
  24.  
    line-height: 178px;
  25.  
    text-align: center;
  26.  
    }
  27.  
    .avatar {
  28.  
    width: 178px;
  29.  
    height: 178px;
  30.  
    display: block;
  31.  
    }
  32.  
    </style>
  33.  
     
  34.  
    </head>
  35.  
    <body>
  36.  
    <div id="con">
  37.  
    <el-upload
  38.  
    class="avatar-uploader"
  39.  
    //注意此处的跳转网页
  40.  
    action="fileUp01"
  41.  
    :show-file-list="false"
  42.  
    :on-success="handleAvatarSuccess"
  43.  
    :before-upload="beforeAvatarUpload">
  44.  
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
  45.  
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  46.  
    </el-upload>
  47.  
    </div>
  48.  
    </body>
  49.  
    <script>
  50.  
    var app=new Vue({
  51.  
    el:"#con",
  52.  
    data:{
  53.  
    imageUrl: ''
  54.  
    },
  55.  
    methods: {
  56.  
    //上传成功后触发的方法
  57.  
    handleAvatarSuccess(res, file) {
  58.  
    //此处进行数据修改
  59.  
    this.imageUrl =res.date;
  60.  
    },
  61.  
    //上传前触发的方法
  62.  
    beforeAvatarUpload(file) {
  63.  
    const isJPG = file.type === 'image/jpeg';
  64.  
    const isLt2M = file.size / 1024 / 1024 < 2;
  65.  
     
  66.  
    if (!isJPG) {
  67.  
    this.$message.error('上传头像图片只能是 JPG 格式!');
  68.  
    }
  69.  
    if (!isLt2M) {
  70.  
    this.$message.error('上传头像图片大小不能超过 2MB!');
  71.  
    }
  72.  
    return isJPG && isLt2M;
  73.  
    }
  74.  
    }
  75.  
    })
  76.  
    </script>
  77.  
    </html>
学新通

3.2 后台的接口

  1.  
    @RequestMapping("fileUp01")
  2.  
    @ResponseBody
  3.  
    public CommonResult test02(MultipartFile file, HttpSession session){
  4.  
    try{
  5.  
    //1.获取上传到服务器的文件夹路径
  6.  
    String path = session.getServletContext().getRealPath("path1");
  7.  
    File file = new File(path1);//此路径下创建文件对象
  8.  
    if(!file.exists()){
  9.  
    file.mkdirs();
  10.  
    }
  11.  
    String filename=UUID.randomUUID().toString().replace("-","")
  12.  
    file.getOriginalFilename();//图片名
  13.  
    File file1 = new File(path "/" filename);
  14.  
    file.transferTo(file1);
  15.  
    CommonResult success = CommonResult.success("http://localhost:8080/keqianceSpring/path1/" filename);
  16.  
    return success;
  17.  
    } catch (IOException e) {
  18.  
    e.printStackTrace();
  19.  
    }
  20.  
    CommonResult error = CommonResult.error(500);
  21.  
    return error;
学新通

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

  1.  
    @Controller
  2.  
    public class UploadFile02 {
  3.  
    @RequestMapping("/load02")
  4.  
    @ResponseBody
  5.  
    public CommonResult test01(MultipartFile file, HttpSession httpSession) throws IOException {
  6.  
    String path = httpSession.getServletContext().getRealPath("path");
  7.  
    File file1 = new File(path);
  8.  
    if(!file1.exists()){
  9.  
    file1.mkdirs();
  10.  
    }
  11.  
    String pName=UUID.randomUUID().toString().replace("-","") file.getOriginalFilename();
  12.  
    File file2 = new File(file1, pName);
  13.  
    if(!file2.exists()){
  14.  
    file2.createNewFile();
  15.  
    }
  16.  
    try(InputStream inputStream=file.getInputStream();
  17.  
    OutputStream outputStream=new FileOutputStream(file2)){
  18.  
    byte[] b=new byte[1024];
  19.  
    int len=0;
  20.  
    while((len=inputStream.read(b))!=-1){
  21.  
    outputStream.write(b,0,len);
  22.  
    }
  23.  
    outputStream.flush();
  24.  
    outputStream.close();
  25.  
    inputStream.close();
  26.  
    return CommonResult.success("http://localhost:8080/keqianceSpring/path/" pName);
  27.  
    }catch (Exception e){
  28.  
    e.printStackTrace();
  29.  
    return CommonResult.error("上传失败");
  30.  
    }
  31.  
    }
  32.  
    }
学新通

CommonResult

  1.  
    @Data
  2.  
    @AllArgsConstructor
  3.  
    @NoArgsConstructor
  4.  
    public class CommonResult {
  5.  
    private final static int success=200;
  6.  
    private final static int error=500;
  7.  
    private final static int not_fount=404;
  8.  
    private int code;
  9.  
    private String msg;
  10.  
    //注意此处的date,后续要是不能打印注意看此处
  11.  
    private Object date;
  12.  
     
  13.  
    public static CommonResult success(Object date){
  14.  
    return new CommonResult(CommonResult.success,"success",date);
  15.  
    }
  16.  
    public static CommonResult error(Object date){
  17.  
    return new CommonResult(CommonResult.error,"未知错误,请联系管理员",date);
  18.  
    }
  19.  
    public static CommonResult notFount(){
  20.  
    return new CommonResult(CommonResult.not_fount,"资源不存在",null);
  21.  
    }
  22.  
    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggkkac
系列文章
更多 icon
同类精品
更多 icon
继续加载