四、springMVC第四节

一、普通的文件上传到OSS文件服务器

        将文件上传到阿里云的OSS文件服务器,我们可以看官方提供的阿里云文档。

(1)导入官方给的依赖jar包。这里直接给你不用去找了,官网上也有


    com.aliyun.oss
    aliyun-sdk-oss
    3.10.2

(2)代码测试

四、springMVC第四节_第1张图片

        点击简单上传以后,往下找到第三个---上传文件流。可以搞一个Demo测试类,将其中的代码复制进去。

四、springMVC第四节_第2张图片

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();
            }
        }
    }
}    

 里面需要修改的几个地方:

  • Endpoint:复制这个地址:在你的OSS的backet中找到你要存储的文件夹,点进去。然后点击概述,找到这个网址,复制到Endponit中。
  • accessKeyId,ccessKeySecret:密钥,阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。密钥的申请位置上一篇文章已经讲过这里不多赘述。

  • bucketName:你想要上传到的文件夹的名称

  • objectName:上传的文件的文件名。可以包含多级目录。例如a/b/c/xxx.jpg

  • filePath:指定你想要上传的文件的本地路径

        全部改好以后,直接运行你的Demo,idea没有提示错误的话,你的文件就已经上传到你指定的文件夹下了。如果没有,仔细查看上面要修改的地方有没有写错。

        (3)正真我们在使用的时候,肯定不能手写他的文件名,也不能自己写他的路径。所以我们需要改动一下我们的代码。

String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "xxxxxx";
        String accessKeySecret = "xxxxxxxxx";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "xxxxx";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        Calendar calendar = Calendar.getInstance();
        String objectName = calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE) + "/" + UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);

        上传文件的文件名我们可以在他的前面根据日期的不同来使他放入不同的文件夹中,同一天的文件放入同一个文件夹。UUID工具+file.getOriginalFilename使其文件名变为随机生成且唯一的名字+文件原始名称+文件后缀名。最后inputStream只需使其等于file.getInputStream即可。

        (4)将其封装成一个工具类。之后再使用的地方直接调用即可。让改工具类返回一个字符串

,该字符串就是文件在阿里云服务器中的最终路径。

package com.lrs.utils;

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

import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

/**
 * @作者:刘壬杉
 * @创建时间 2022/6/10
 **/
public class OSSUtil {
    public static String upload(MultipartFile file) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "xxxxxx";
        String accessKeySecret = "xxxxxxxxx";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "xxxxxx";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        Calendar calendar = Calendar.getInstance();
        String objectName = calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE) + "/" + UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
        return url;
    }
}

二、elementUI异步上传OSS服务器

(1)前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登录页面
    <%--引入css样式--%>
    
    <%--引入vue的js--%>
    
    <%--引入axios的js--%>
    
    <%--引入elementui的js--%>
    
    <%--引入qs--%>
    
    


    

(2)Controller接口

package com.lrs.controller;

import com.lrs.util.CommenResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @作者:刘壬杉
 * @创建时间 2022/6/10
 **/
@Controller
public class UploadController {
    @RequestMapping(value = "upload01")
    @ResponseBody
    public CommenResult upload(HttpServletRequest request, MultipartFile file){
        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);
            Object data = "http://localhost:8080/s/upload/"+filename;
            CommenResult result = new CommenResult(2000,"上传成功",data);
            return  result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        CommenResult result = new CommenResult(5000,"上传失败",null);
        return  result;
    }
}

三、模拟添加用户信息查询信息(包含头像上传)

       这里包含了mybatis技术和springMVC技术的总和案列。mybatis运用generator代码生成器生成了实体类,UerMapper和dao层(包含简单的crud)。这里直接把工程发给大家让大家查看。(上传头像部分的工具类里的密钥我做了隐藏,大家改成自己的服务器和自己的数据库再使用)

springmvc+mybatis+elementui+vue的模拟添加用户,查询用户-Java文档类资源-CSDN下载icon-default.png?t=M4ADhttps://download.csdn.net/download/lrs998563/85609392

四、零散补充(不影响使用)

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

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

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

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

        

你可能感兴趣的:(springMVC,html,java,spring)