java api 接收保存图片到本地

Posted 张学涛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java api 接收保存图片到本地相关的知识,希望对你有一定的参考价值。

    /**
    * 保存图片
    */
    @CrossOrigin(origins = {"*", "null"})
    @RequestMapping(value = "uploadPic", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String uploadPic(MultipartFile photo) {
        AppRootBean appRootBean = new AppRootBean();
        String resultString = "";
        MDC.put("requestType","uploadPic");
        logger.info("接收前端data:{}", photo);

        String s1="";
        try {
            if (null!=photo&&!photo.isEmpty())
            {
                MakeOrderNum makeOrderNum = new MakeOrderNum();
                String wx_photo = makeOrderNum.makeOrderNum("wx_photo");
                s1 = PicUtil.singleFileUpload(photo,wx_photo);

            }

            if (StringUtils.isEmpty(s1))
            {
                resultString = appRootBean.sendRoot(new Object(), ErrorCode.MSG_UPPHONE_CODE_ERROR.getResponseCode(),
                        ErrorCode.MSG_UPPHONE_CODE_ERROR.getResponseMsg());
            }else {
                resultString = appRootBean.sendRoot(s1, ErrorCode.MSG_OK.getResponseCode(),
                        ErrorCode.MSG_OK.getResponseMsg());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        logger.info("上送图片" + resultString);
        MDC.clear();
        return resultString;
    }

 

工具类:

package com.weixiu.jingwei.utils;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: 张学涛
 * @Date: 2019-08-23 10:25
 * @Version 1.0
 */
public class PicUtil {

    private static String UPLOAD_FOLDER = "/opt/wxPhoto/";
    public static String singleFileUpload(MultipartFile pc1,String picName) throws IOException {
        // logger.debug("传入的文件参数:{}", JSON.toJSONString(file, true));
        if (Objects.isNull(pc1) || pc1.isEmpty()) {

            return "";
        }
        try {
            byte[] bytes = pc1.getBytes();

            Path path = Paths.get(UPLOAD_FOLDER + "/");

            if (!Files.isWritable(path)) {
                Files.createDirectories(path);
            }
            String extension = getFileExtension(pc1);  //获取文件后缀

            UUID uuid = UUID.randomUUID();
            String str = uuid.toString();

            String picname = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
            String relativeAddr = picname+picName + extension;  //唯一的名字接上后缀
            Thumbnails.of(pc1.getInputStream()).size(1920, 1200)    //写入
                    .outputQuality(1.0f).toFile(path + "/" + relativeAddr);
//            Thumbnails.of(pc1.getInputStream())  //写入
//                    .outputQuality(1.0f).toFile(path + "/" + relativeAddr);
            //logger.debug("文件写入成功...");
            return Paths.get(path + "/" + relativeAddr).toString();

        } catch (IOException e) {
//            e.printStackTrace();
            return "null";
        }
    }

    //写一个删除方法,你们可以看情况修改
    public static String deFile(String path) {
        String resultInfo = null;
        Map<String, Object> modelMap = new HashMap<String, Object>();

        // String sb =area.getAreaName();;
        // sb.replace("/","\");
        //String sb1 = "F:\photos\蛇皮玩意儿\123\瞎把.jpg";
        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                resultInfo = "1-删除成功";
            } else {
                resultInfo = "0-删除失败";
            }
        } else {
            resultInfo = "文件不存在!";
        }
//        imgDomainURL: http://10.40.0.53:8888/jeecg-boot/sys/common/view/
        return resultInfo;

    }

    public static boolean deleteDirectory(String dirPath) {// 删除目录(文件夹)以及目录下的文件
        // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        boolean flag = false;
        String a = null;
        if (!dirPath.endsWith(File.separator)) {
            dirPath = dirPath + File.separator;
            System.out.println("没有后缀符号‘/‘");

        }
        File dirFile = new File(dirPath);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            System.out.println("不是目录");
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();// 获得传入路径下的所有文件
        for (int i = 0; i < files.length; i++) {// 循环遍历删除文件夹下的所有文件(包括子目录)
            if (files[i].isFile()) {// 删除子文件
                a = deFile(files[i].getAbsolutePath());
                System.out.println(files[i].getAbsolutePath() + " 目录文件删除成功");
                if (!flag) {
                    break;// 如果删除失败,则跳出
                }
            } else {// 运用递归,删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) {
                    break;// 如果删除失败,则跳出
                }
            }
        }
        if (!flag) {
            return false;
        }
        if (dirFile.delete()) {
            // 删除当前目录
            return true;
        }
        return false;
    }

    private static String getFileExtension(MultipartFile File) {
        String originalFileName = File.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));

    }


}

 

以上是关于java api 接收保存图片到本地的主要内容,如果未能解决你的问题,请参考以下文章

根据图片的url地址下载图片到本地保存代码片段

如何将S/4HANA系统存储的图片文件用Java程序保存到本地

java:servlet接收图片,并把它保存到数据库中

wdVBA保存图片到本地API

java通过百度地图 获取静态图片 如何保存到本地

java实现图片上传至服务器并显示,如何做?