springmvc-文件上传

1. 文件上传的原理

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

(1)导入文件上传的jar包-commons-fileupload

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

(2) 创建jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <!--method必须是post,input类型必须是file,必须要有name属性-->
    <form method="post" action="upload" enctype="multipart/form-data">
        <input type="file" name="myfile"/><br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>

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

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"/>
    </bean>

(4)创建upload01接口方法

@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile myfile, HttpServletRequest request) throws Exception{
        String path = request.getSession().getServletContext().getRealPath("upload");
        System.out.println(path); //上传文件的本地路径
         //新建文件夹
        File file=new File(path);
        //检测。如果文件不存在,将会创建一个文件
        if(!file.exists()){
            file.mkdirs();
        }
           //生成随机的字符串
           //replace:替换
        String fileName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        File target = new File(path+"/"+fileName);
        myfile.transferTo(target);
        return "";
    }

}

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

(1)页面的布局

<%--
  Created by IntelliJ IDEA.
  User: xu
  Date: 2022/6/9
  Time: 18:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <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/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="app">
        <el-upload
                class="avatar-uploader"
                action="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>
    <script>
        var app = new Vue({
            el:"#app",
            data:{
                imageUrl:"",
            },
            methods:{
                handleAvatarSuccess(res, file) {
                    this.imageUrl = res.data;
                },
                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>

(2)后端的页面

@RequestMapping("/upload02")
    //输出JSon格式
    @ResponseBody
    //MultipartFile file:前端页面默认的name为file
    public Map upload02(MultipartFile file, HttpServletRequest request){
        try {
            String path = request.getSession().getServletContext().getRealPath("upload");
            File file1=new File(path);
            if(!file1.exists()){
                file1.mkdirs();
            }
            String fileName=UUID.randomUUID().toString().replace("-","")
                    +file.getOriginalFilename();
            File target = new File(path+"/"+fileName);
            file.transferTo(target);
            Map map=new HashMap();
            map.put("code",2000);
            map.put("msg","上传成功");
            //路径为服务器的路径
            map.put("data","http://localhost:8080/upload/"+fileName);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map=new HashMap();
        map.put("code",5000);
        map.put("msg","上传失败");
        return map;
    }

3.本地文件上传到OOS

如何使用OOS?

此处使用的是阿里云的OOS

(1)注册阿里云的账户

(2)

 (3)图片中的文档能够查询如何使用OOS

 (4)

(5) (6)导入依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>

 (7)

public class OssUtil {
    public static String upload(MultipartFile myfile) throws Exception{
         Endpoint以华东1(杭州)为例,其它Region请按实际情况填写
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        //阿里云密钥账号
        String accessKeyId = "yourAccessKeyId";
         //阿里云密钥密码
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "xusl";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。

        String objectName =filName(myfile);
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        //String filePath= "D:\\鼠标指针\\1.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream =myfile.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
//        String url = "https://"+bucketName+"."+endpoint+"/"+objectName;
//        request.setAttribute("imgUrl",url);
        //https://xusl.oss-cn-hangzhou.aliyuncs.com/bz.jpg
        String url="https://"+bucketName+"."+endpoint+"/"+objectName;
        return url;
    }

    private  static String filName(MultipartFile myfile){
        Calendar calendar=Calendar.getInstance();
        String name= calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE)+"/"
                + UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        return name;
    }
}

4.使用element-ui+vue+OOS上传文件

(1)前端页面

<%--
  Created by IntelliJ IDEA.
  User: xu
  Date: 2022/6/12
  Time: 16:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link type="text/css" rel="stylesheet" href="css/index.css"/>
    <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/index.js"></script>
    <script type="text/javascript" src="js/axios.min.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="app">
        <el-form  label-width="80px" :model="userForm">
            <el-form-item label="头像:">
                <el-upload
                        class="avatar-uploader"
                        action="uploadAvatar"
                        :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>
            </el-form-item>
            <el-form-item label="账号:">
                <el-input v-model="userForm.name"></el-input>
            </el-form-item>
            <el-form-item label="密码:">
                <el-input v-model="userForm.pwd"></el-input>
            </el-form-item>
            <el-form-item label="地址:">
                <el-input v-model="userForm.address"></el-input>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" @click="onSubmit">添加</el-button>
            </el-form-item>
        </el-form>
    </div>
</body>
<script>
    var app=new Vue({
        el:"#app",
        data:{
            userForm:{},
            imageUrl:""
        },
        methods:{
            handleAvatarSuccess(result,file){
                this.imageUrl=result.data;
                //为表单对象添加头像地址的属性
                this.userForm.avatarUrl=this.imageUrl;
            },
            //提交
            onSubmit(){
                axios.post("addUser",this.userForm).then(function(result){
                    console.log(result)
                });
            },
            //上传前触发的方法
            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>

(2)Controller层代码

package com.xsl.controller;

import com.xsl.entity.User;
import com.xsl.util.CommonResult;
import com.xsl.util.OssUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

//@Controller
@RestController
public class Upload03 {
    @RequestMapping("uploadAvatar")
    @ResponseBody
    public CommonResult uploadAvatar(MultipartFile file){
        try {
            String avatar = OssUtil.upload(file);
            return new CommonResult(2000,"上传成功",avatar);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult(5000,"上传失败",null);
    }

    @PostMapping("addUser")
    //@RequestMapping("addUser")
    @ResponseBody
    public CommonResult addUser(@RequestBody User user){
        System.out.println(user);

        return new CommonResult(2000,"上传成功",null);
    }
}

(3)utils层代码

封装的OOS类

package com.xsl.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

public class OssUtil {
    public static String upload(MultipartFile myfile) throws Exception{
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tHqTysVnNH81TYcY2yd";
        String accessKeySecret = "mU28irg6XMfzsvHzCSUGh1HSeHNAd2";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "xusl";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。

        String objectName =filName(myfile);
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        //String filePath= "D:\\鼠标指针\\1.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream =myfile.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
//        String url = "https://"+bucketName+"."+endpoint+"/"+objectName;
//        request.setAttribute("imgUrl",url);
        //https://xusl.oss-cn-hangzhou.aliyuncs.com/bz.jpg
        String url="https://"+bucketName+"."+endpoint+"/"+objectName;
        return url;
    }

    private  static String filName(MultipartFile myfile){
        Calendar calendar=Calendar.getInstance();
        String name= calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE)+"/"
                + UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        return name;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值