Java 接收Vue前端上传base64图片数据并存放在本地

发布时间:2023年12月18日

前端代码

let base64Data = "图片base64数据";
const formData = new FormData();
formData.append("biz", 'person');
formData.append("base64", base64Data);
let url = config.configData.api_url  + "/business/common/upByBase64";
httpFile(url,formData).then((res) => {
      resolve(res);
})

httpFile函数

function httpFile (path = '', formData = {}) {
  let token = sessionStorage.getItem("token");
  return new Promise(function (resolve, reject) {
    axios.post(path + "/", formData, {headers: {"token": token}, "Content-type":"multipart/form-data",timeout:120000})
      .then(function (response) {
        check(response.data);
        resolve(response)
      })
      .catch(function (error) {
        reject(error)
      })
  })
}

后端代码

@PostMapping(value = "/upByBase64")
    public Result<?> upByBase64(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String biz = "";
        if(StringUtils.isNotEmpty(request.getParameter("biz"))){
            biz = request.getParameter("biz");
        }else{
            biz = "other";
        }
        String base64str = request.getParameter("base64");
        if (base64str.contains("data:image")) {
            base64str = base64str.substring(base64str.indexOf(",") + 1);
        }
        base64str = base64str.replace("\r\n", "");
        InputStream inputStream=null;
        OutputStream outputStream = null;

        try {
            // 从inputStream读取数据
            byte[] bytes = Base64.getDecoder().decode(base64str);
            inputStream = new ByteArrayInputStream(bytes);
            String newFile =  UUID.randomUUID().toString().replace("-", "") + ".png";
            savePath = biz + File.separator + newFile;
            // 创建本地文件输出流
            outputStream = new FileOutputStream(uploadpath + File.separator + savePath );

            byte[] buffer = new byte[1024];
            int bytesRead;
            // 将数据从inputStream写入outputStream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            System.out.println("文件转存成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭输入流和输出流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return Result.ok(savePath);

    }

文章来源:https://blog.csdn.net/gdgztt/article/details/135069351
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。