上传用base64字符串

@RequestMapping("/upload/image")
public Object uploadFile(@RequestBody JSONObject a) throws IOException {

File file = null;
try {
file = base64ToFile(a.getString("file"));
} catch (Exception e) {
e.printStackTrace();
}
String url = FileUtil.uploadFile(file);

return url;
}


public File base64ToFile(String base64) throws Exception {
if(base64.contains("data:image")){
base64 = base64.substring(base64.indexOf(",")+1);
}
base64 = base64.toString().replace("\r\n", "");
//创建文件目录
String prefix=".jpeg";
File file = File.createTempFile(UUID.randomUUID().toString(), prefix);
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(base64);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
}finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}



//上传图片
    $('#createImage').on('click',function(){
        let param = new FormData(); //创建form对象
        let signName = document.getElementById("signName");
        let twojz = $('#signName').createSignature();
        let blob = dataURItoBlob($('#signName').createSignature());
        console.log($('#signName').createSignature());
        console.log(blob);
        let pmm = {"file":twojz};
        let pmmStr = JSON.stringify(pmm);
        param.append('file', blob, "--image" + new Date().getTime() + "client_signature.png");
        let pararar = {"fileStream":blob};
        let par = JSON.stringify(pararar);
        $.ajax({
                url:"http://localhost:8080/upload/image" , // 请求路径
                type:"POST" , //请求方式
                processData : false,
                contentType : "application/json",
                async:false,
                data:pmmStr,
                beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG1pbiIsImV4cCI6MTY1MDMwNzg1MH0.ciKm2SQUGbo2Olk01EnmzVnJVdON0VOgULkLP-L5OMM");
             },
                success:function (data) {
                    alert(data);
                },//响应成功后的回调函数
                error:function () {
                    alert("出错啦...")
                },//表示如果请求响应出现错误,会执行的回调函数

                dataType:"text"//设置接受到的响应数据的格式
                    });
                   
    });

});
</script>
posted @   清风竹慕  阅读(217)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示