Spring Boot文件上传

1、前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <h1>文件上传</h1>
    <form action="/upload" id="uploadform" enctype="multipart/form-data"method="post">
        <input name="dir" value="bbs">
        <input name="file" type="file" onchange="toUpload()" multiple>
    </form>
<script>
    function toUpload() {
        document.getElementById("uploadform").submit();
    }
</script>
</body>
</html>

2、后端页面

Service层

依赖

    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>3.10.2</version>
    </dependency>
@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Override
    public String uploadfile(MultipartFile multipartFile, String str) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String imgSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename= UUID.randomUUID().toString()+imgSuffix;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String datePath = dateFormat.format(new Date());
        File targetFile = new File("D://LJH/" + str+"/"+datePath);
        if (!targetFile.exists())
            targetFile.mkdirs();
        File file = new File(targetFile, newFilename);
        multipartFile.transferTo(file);
        return "http://localhost:8080/upload/"+str+"/"+datePath+"/"+newFilename;
    }
}

controller层

 @PostMapping("/upload")
    @ResponseBody
    public String Upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        if (multipartFile.isEmpty())
            return "文件为空";
        String str=request.getParameter("dir");
        return uploadFileService.uploadfile(multipartFile,str);
        
    }

OSS

public String OssUpload(MultipartFile multipartFile) throws IOException {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tRHjXo6cYh9XyfPcWwF";
        String accessKeySecret = "VzAx9ccw5BwFunu9CIByVAAJBHCMdJ";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String backetName="demo";
        //如果桶不存在,动态创建桶
        if(!ossClient.doesBucketExist(backetName)){
            //创建bucket
            ossClient.createBucket(backetName);
            //设置oss实例的访问权限,公共读
            ossClient.setBucketAcl(backetName, CannedAccessControlList.PublicRead);
        }
        InputStream inputStream = multipartFile.getInputStream();
        String originalFilename = multipartFile.getOriginalFilename();
        String imgSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename= UUID.randomUUID().toString()+imgSuffix;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String datePath = dateFormat.format(new Date());
        String fileUrl=datePath+"/"+newFilename;

       PutObjectRequest putObjectRequest = new PutObjectRequest(backetName, fileUrl, inputStream);
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return "https://"+backetName+"."+endpoint+"/"+fileUrl;
    }

WangEditor

controller层

@PostMapping("/wangeditor")
    @ResponseBody
    public Map<String,String> wangeditor(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        if (multipartFile.isEmpty())
            return null;
        String str=request.getParameter("dir");
        //return uploadFileService.uploadfile(multipartFile,str);
        HashMap<String, String> map = new HashMap<>();
        map.put("url",ossService.OssUpload(multipartFile));
        return map;
    }

前端页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WangEditor</title>
</head>
<body>
<div id="div1">
    <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"></script>
<!-- 引入 wangEditor.min.js -->
<script type="text/javascript">
    const E = window.wangEditor
    const editor = new E('#div1')
    // 或者 const editor = new E( document.getElementById('div1') )
    // 配置 server 接口地址
    editor.config.uploadImgServer = '/wangeditor'
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
    editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    editor.config.uploadImgParams = {
        dir: 'bbs'
    }
    editor.config.uploadFileName = 'file'
    editor.config.uploadImgHooks = {
        // 上传图片之前
        before: function(xhr) {
            return true
        },
        // 图片上传并返回了结果,图片插入已成功
        success: function(xhr) {
            console.log('success', xhr)
        },
        // 图片上传并返回了结果,但图片插入时出错了
        fail: function(xhr, editor, resData) {
            console.log('fail', resData)
        },
        // 上传图片出错,一般为 http 请求的错误
        error: function(xhr, editor, resData) {
            console.log('error', xhr, resData)
        },
        // 上传图片超时
        timeout: function(xhr) {
            console.log('timeout')
        },
        // 图片上传并返回了结果,想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
        customInsert: function(insertImgFn, result) {
            // result 即服务端返回的接口
            console.log('customInsert', result)

            // insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
            insertImgFn(result.url)
        }
    }
    editor.create()
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值