TouchUI h5上传图片或文件

跨越,上传文件
ui.request
图片转=10.5ptBase64 ——> 后端转换成文件
 
@PostMapping("/upload")
@ResponseBody
public Result fileUpload(){
JSONObject jsonByRequest = MyRequestUtils.getJsonByRequest(request);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String imgdata = (String) jsonByRequest.get("imgdata");
String imgInfo = imgdata.split(",")[0];
String base64Data = imgdata.split(",")[1];
String imgTypeSub = imgInfo.substring(imgInfo.indexOf("/")+1, imgInfo.indexOf(";"));
String imgType ="";
if("png".equals(imgTypeSub)){
imgType = ".png";
}else {
imgType = ".jpg";
}

if (base64Data == "") //图像数据为空
{
return new Result(500, "上传数据不能为空", "");
}
byte[] bytes = Base64.decodeBase64(base64Data);
for(int i=0;i<bytes.length;++i)
{
if(bytes[i]<0)
{//调整异常数据
bytes[i]+=256;
}
}
String uuid = UUID.randomUUID().toString().replace("-", "");
String newFileName = uuid + imgType;
String fileTempDir = MySystemLang.FILE_TEMP;
File dest = new File(fileTempDir + "/"+newFileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
OutputStream out = null;
try {
out = new FileOutputStream(dest);
out.write(bytes);
out.flush();
out.close();

} catch (Exception e) {
e.printStackTrace();
}
String show = "/static/img/temp/" +newFileName;
return new Result(200,"上传成功",show);
}
request.getAttribute() 获取不到值解决
public static JSONObject getJsonByRequest(ServletRequest request){

BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try
{
try {
br = request.getReader();
} catch (IOException e) {
e.printStackTrace();
}
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (null != br)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

return JSONObject.parseObject(sb.toString());
}

 
前端代码

<input type="file" id="fileSelector" multiple accept="image/*" bindchange="handleInputChange($event)"/>
 
方法
    handleInputChange(e){
    var file = e.target.files[0];
    var reader = new FileReader();
    var imgdata = '';
    reader.readAsDataURL(file);
    reader.onload = function(){
    //读取完毕后输出结果
    // console.log(this.result);
     var base64Data = this.result;
      ui.request({
        url: uploadUrl, 
        method: "POST",
          header: {
            'content-type': 'application/jsont=utf-8'
          },
        data: {
          "imgdata":base64Data
        },
        success: function (res) {
          console.log(res.data)
        }
    })
      
    }
  },

 

 

 

 
 
已邀请:

要回复问题请先登录注册



QQ:378966107

邮箱:frank@uileader.com

微信进交流群 加小助手微信进交流群