本地文件上传&阿里云上传和下载文件

package com.xyz.mop.manage.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.xyz.mop.manage.bean.common.Ret;
import com.xyz.mop.manage.bean.enums.ResultEnum;
import com.xyz.mop.manage.exception.BusinessException;
import com.xyz.mop.manage.util.ResultUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lianJiaYu
 * @date 2021/8/11 9:16
 */
@RestController
@RequestMapping("/updateFile")
public class UploadController {

    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    private static String endpoint = "你自己对应的地区";

    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    private static String accessKeyId = "你自己的accessKeyId*******";

    private static String accessKeySecret = "你自己的accessKeySecret*******";

    private static String bucketName = "你自己的bucketName";


    private OSS ossClient = null;
    {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    }

    /**
     * 本地文件上传
     *
     * @param file
     * @param req
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Ret upload(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IOException {
        Map<String, String> map = new HashMap<>();
        // 源文件名
        String fileName = file.getOriginalFilename();
        String yyyyMMdd = DateUtil.format(new Date(), "yyyyMMdd");
        //本地上传路径
        String filePath = "D:/java/IDEA/IDEAWork/mopmanage/src/main/resources/static/upload/" + yyyyMMdd + "/";
        //服务器路径
        //String filePath = "/data/file/upload"+yyyyMMdd+"/";
        //本地项目动态路径根路径,在 classes/static/upload
        //String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/upload/" + yyyyMMdd + "/";
        FileUtil.mkdir(filePath);
        //String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + yyyyMMdd + fileName;
        //String url = "http://localhost:10001/mop-manage/1.jpg";
        //System.out.println("filePath + fileName:" + filePath + fileName);
        try {
            file.transferTo(new File(filePath + fileName));
        } catch (Exception e) {
            //log.error("【图片上传】上传失败,path=,{},errormessage:{}", filePath + fileName, e.getMessage());
            throw new BusinessException(ResultEnum.IMGERROR3);
        }
        map.put("fileName", fileName);
        map.put("imgPath", filePath + fileName);
        //map.put("url", url);
        return ResultUtil.success(map);
    }

    /**
     * 阿里云文件上传
     *
     * @param file
     * @param req
     * @return
     * @throws IOException
     */
    @PostMapping("uploadAliYun")
    public Ret upload1(@RequestParam("file") MultipartFile file, HttpServletRequest req) throws IOException {
        String fileName = file.getOriginalFilename();
        // 创建OSSClient实例。
        //OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 填写网络流地址。
        //InputStream inputStream = new URL("https://www.aliyun.com/").openStream();
        InputStream inputStream = file.getInputStream();
        // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, "img/" + fileName, inputStream);
        String url = "https://even-boy.oss-cn-shanghai.aliyuncs.com/img/" + fileName;
        // 关闭OSSClient。
        ossClient.shutdown();
        return ResultUtil.success(url);
    }

    /**
     * 阿里云文件下载
     *
     * @param fileName
     * @param res
     * @return
     * @throws IOException
     */
    @GetMapping("downloadAliYun")
    public Ret download(String fileName, HttpServletResponse res) throws IOException {
        // 创建OSSClient实例。
        /// OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = null;
        OutputStream os = null;
        try {

            OSSObject object = ossClient.getObject(new GetObjectRequest(bucketName, "img/" + fileName));
            System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
            inputStream = object.getObjectContent(); //获取流

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();

            byte[] data = outStream.toByteArray();
            res.reset();
            res.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            res.setContentType("application/octet-stream");
            os = res.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.DBNOTEXIST);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (os != null) {
                os.close();
            }
            ossClient.shutdown();
        }
        return ResultUtil.success();
    }


}

posted @ 2021-08-11 19:49  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源