package com.unis.crk.hardware.util;


import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * zy
 * base64图片上传
 */
public class HardwareUtil {
   // private static final String URL = "http://127.0.0.1";//服务器地址，按以前的方法获取图片时ip前台获取

    //前台不需要对base64做任何处理(换行问题未作测试)
    public static String upOneByYourUrlUseBase64(String files/*文件*/, String yourUrl/*存储地址*/) throws FileNotFoundException {
        int n = 0;
        //经过尝试.replace()不可用，替换空格方法如下
        StringBuffer str = new StringBuffer(files);
        while (str.indexOf(" ", n) != -1) {
            n = str.indexOf(" ", n);//获得空格的索引
            str.deleteCharAt(n);//删除对应索引的空格
            str.insert(n, "+");//在相应位置插入
            n = n + 1;
        }
        files = String.valueOf(str);
        if (files.indexOf("data:") == -1) {
            files = "data:image/jpg;base64," + files;
        }
        MultipartFile file = Base64MultipartFile.base64ToMultipart(files);
        String url = /*URL + "/" +*/ yourUrl + "/";
        String ReturnMessage = null;
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        if (!file.isEmpty()) {
            try {
                File fi = new File(path.getAbsolutePath(), "static/" + yourUrl + "/");
                if (!fi.exists()) {
                    fi.mkdirs();
                }//不在就创建
                String fik = file.getOriginalFilename();
                int a = fik.indexOf(".");
                String fileName = file.getOriginalFilename().substring(a);//截取字符串
                String address = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
                FileOutputStream f = new FileOutputStream(fi + "/" + address + fileName);
                BufferedOutputStream out = new BufferedOutputStream(f);
                System.out.println(url + address + fileName);
                ReturnMessage = url + address + fileName;
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "error";
            } catch (IOException e) {
                e.printStackTrace();
                return "error";
            }
            return ReturnMessage;
        } else {
            return "error";
        }
    }

}





