SpringMVC中的文件上传


目录

1、将文件上传到本地服务器

2、Element+vue+axios完成文件上传

3、文件上传到oss阿里云的服务器

4、琐碎的内容


1、将文件上传到本地服务器

流程:(1)文件上传的依赖

  <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属性
   --%>
   <form method="post" action="upload01" enctype="multipart/form-data">
       <input type="file" name="myfile"/>
        <input type="submit" value="提交"/>
   </form>

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

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

 (4)创建接口方法

 @RequestMapping("upload01")
    @ResponseBody
    //此处MultipartFile的参数名必须和<input type="file" name="myfile"/>中name属性相同
    public String  upload01(MultipartFile myfile, HttpServletRequest request)throws Exception{
         //得到本地服务目录的地址
        String pat = request.getSession().getServletContext().getRealPath("upload");
        //判断该目录是否存在
        File file = new File(pat);
        if (!file.exists()){
            file.mkdirs();
        }
        //把myfile保存到本地服务中某个文件夹下。 缺点:文件的名称
        String filename= UUID.randomUUID().toString().replace("-","")
                +myfile.getOriginalFilename();
        File target = new File(pat+"/"+filename);
        myfile.transferTo(target);
        System.out.println(pat);
        return "";
    }

2、Element+vue+axios完成文件上传

(1)页面布局

element的网址:Element - The world's most popular Vue UI framework

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!--引入element得css样式-->
    <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>
<body>
    <div id="app">
        <%--action:文件上传的路径--%>
        <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 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>

<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>
</html>

(2)后台的接口

 @RequestMapping("/upload02")
    @ResponseBody
    public Map upload02(MultipartFile file, HttpServletRequest request) {
        try {
            //1.获取上传到服务器的文件夹路径
            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 (Exception e){
            e.printStackTrace();
        }
        Map map=new HashMap();
        map.put("code",5000);
        map.put("msg","上传失败");
        return map;
    }

3、文件上传到oss阿里云的服务器

上传到本地服务器的缺点: 如果搭建集群,导致文件无法在集群中共享。 它的解决方法就是把文件专门上传到一个文件服务器上,这些tomcat服务器都操作同一个文件服务器。

(1)获取密钥

(2)创建文件存储

 (3)获取外网网址

(4)上传的代码以及所用的依赖

 

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "D:\\localpath\\examplefile.txt";

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

        try {
            InputStream inputStream = new FileInputStream(filePath);            
            // 创建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();
            }
        }
    }
}                    

 

 

 

4、琐碎的内容

@RestController----类上等价于 @COntroller+@ResponseBody
    该注解下所有的方法都是返回json数据
    
@RequestMapping: 作用: 把请求路径映射到响应的方法上。

@RequestParam(value = "u"):设置你接受的请求参数名。查询参数

@RequestMapping(value = "/addUser",method = RequestMethod.POST)
       method:表示该接口接受的请求方式.不设置可以接受任意请求方式。
       
@GetMapping("addUser"):表示只接受get提交方式的请求     

@RequestBody:把请求的json数据转换为java对象。从前端到后端
@ResponseBody:把java转换为json数据   从后端转前端

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值