栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

七牛云上传,删除和下载文件(Java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

七牛云上传,删除和下载文件(Java)

public class QiNiuUtils {
    private static final String ACCESS_KEY = "**********";
    private static final String SECRET_KEY = "**********";
    private static final String BUCKET = "*****";//空间名称
    private static final String DOMAIN = "*****";//七牛云自己的域名
    private static Configuration configuration;
    private static Client client;
    private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    //上传
    public static String upload(File file, String key)  {
        // 创建上传对象
        Configuration configuration = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(configuration);
        try {
            // 调用put方法上传
            String token = auth.uploadToken(BUCKET);
            if(StringUtils.isEmpty(token)) {
                System.out.println("未获取到token,请重试!");
                return null;
            }
            Response res = uploadManager.put(file,key,token);
            // 打印返回的信息
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            if (res.isOK()){
                return DOMAIN + putRet.key;
            }
        }catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            e.printStackTrace();
            System.out.println("error "+r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                System.out.println("error "+e1.error());
            }
        }
        return null;
    }

    //删除文件
    public static void deleteFile(String fileName){
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        String key = fileName;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(BUCKET, key);
        } catch (QiniuException ex) {
            //如果遇到异常,说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }

    //获取文件下载URL
    @SneakyThrows
    public static String getDownloadUrl(String filename){
        //自己七牛云上的域名
        String domainOfBucket = "******";
        String encodedFileName = URLEncoder.encode(filename, "utf-8").replace("+", "%20");
        String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        return auth.privateDownloadUrl(finalUrl);
    }

    //下载
    public static void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String fileUrl = getDownloadUrl(filename);
        String fileName = filename;
        //设置响应类型
        fileName = URLEncoder.encode(fileName,"UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName);
        //应用程序强制下载
        response.setContentType("application/force-download");
        //读取文件
        OutputStream out = response.getOutputStream();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(fileUrl);
        CloseableHttpResponse httpResp = httpclient.execute(httpGet);
        try{
            HttpEntity httpEntity = httpResp.getEntity();
            response.setContentLength((int) ( httpEntity).getContentLength());
            IOUtils.copy(( httpEntity).getContent(),out);
        }catch(Exception ex){
            httpclient.close();
            ex.printStackTrace();
        }finally{
            out.flush();
            out.close();
        }
    }
@Controller
@Api(tags = "文件控制")
public class FileController {

    @PostMapping("imageUpload")
    @ResponseBody
    @ApiOperation("图片上传")
    public String imageUpload(@RequestParam("file") MultipartFile file) throws IOException {
        //两个Map用于返回规定格式参数
        Map map = new HashMap<>();
        Map map2 = new HashMap<>();
        if (!file.isEmpty()) {
            // 文件原名称
            String origName = file.getOriginalFilename();
            //是否随机名称
            origName = UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
            //判断是否存在目录,保存为本地临时文件
            String pathDir = "D:/data/img/";
            //上传
            File targetFile = new File( pathDir, origName);
            if (!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            String key = origName+ res +origName.substring(origName.lastIndexOf("."));
            String fileSrc = QiNiuUtils.upload(targetFile,key);
            //图片url
            map2.put("src",fileSrc);
            //图片名称,这个会显示在输入框里
            map2.put("title",origName);
            //0表示成功,1失败
            map.put("code",0);
            //提示消息
            map.put("msg","上传成功");
            map.put("data",map2);
            String result = new Gson().toJson(map);
            return result;
        }else {
            map.put("code",1);
            map.put("msg","上传失败");
            map.put("data",null);
            String result = new Gson().toJson(map);
            return result;
        }
    }

    @PostMapping("fileUpload")
    @ResponseBody
    @ApiOperation("文件上传")
    public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        //两个Map用于返回规定格式参数
        Map map = new HashMap<>();
        Map map2 = new HashMap<>();
        if (!file.isEmpty()) {
            // 文件原名称
            String origName = file.getOriginalFilename();
            //判断是否存在目录,保存为本地临时文件
            String pathDir = "D:/data/file/";
            File targetFile = new File( pathDir, origName);
            if (!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
            String res = sdf.format(new Date());
            String key =  origName.substring(0,origName.indexOf("."))+res +origName.substring(origName.lastIndexOf("."));
            //文件上传
            QiNiuUtils.upload(targetFile,key);
            //通过Get方式下载文件
            String downloadHref = "/downloadFile?filename="+key;

            map2.put("src",downloadHref);
            //名称,这个会显示在输入框里
            map2.put("title",origName);
            //0表示成功,1失败
            map.put("code",0);
            //提示消息
            map.put("msg","上传成功");
            map.put("data",map2);
            String result = new Gson().toJson(map);
            return result;
        }else {
            map.put("code",1);
            map.put("msg","上传失败");
            map.put("data",null);
            String result = new Gson().toJson(map);
            return result;
        }
    }

    @PostMapping("fileDelete")
    @ResponseBody
    @ApiOperation("文件删除")
    public void deleteFile(String imgpath,String filepath){
        if(imgpath!=null) {
            String[] path = imgpath.split("/");
            String key = path[3];
            try {
                QiNiuUtils.deleteFile(key);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if(filepath!=null){
            String[] path = filepath.split("/");
            String key = path[3];
            try {
                QiNiuUtils.deleteFile(key);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @GetMapping("downloadFile")
    @ResponseBody
    @ApiOperation("文件下载")
    public void downloadFile(String filename, HttpServletRequest request, HttpServletResponse response){
        try{
            //文件下载
            QiNiuUtils.download(filename,request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/390424.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号