• 关于文件的上传和后台接收


    文件上传与文件显示

    1、图片预览

    前端页面的代码如下:

      <form action="" enctype="multipart/form-data" method="post">
            <input type="file" name="file" id="file" onchange="previewFile(this);"/>
            <input type="text" id="text"/>
            <input type="button" value="上传" id="upload" onclick="uploadImage();">
            <img id="image" name = "img" src="" alt="头像" class="image">
        </form>

     

    js代码:读取文件

    文件一旦开始读取,无论成功或失败,实例的 result 属性都会被填充。如果读取失败,则 result 的值为 null ,否则即是读取的结果,绝大多数的程序都会在成功读取文件的时候,抓取这个值。

     1     /**图片预览*/
     2         function previewFile(file){
     3             if(window.FileReader){
     4                 var reader = new FileReader();
     5             }else{
     6                 alert("浏览器不支持")
     7             }
     8             /**onload事件:文件读取成功触发*/
     9             reader.onload = function (e) {
    10                 document.getElementById('image').src = e.target.result;
    11                 image = e.target.result;
    12                // console.log(image);
    13             };
    14             /**
    15              * readAsDataURL():
    16              * 该方法将文件读取为一段以 data: 开头的字符串,
    17              * 这段字符串的实质就是 Data URL,Data URL是一种将小文件直接嵌入文档的方案。
    18              */
    19             reader.readAsDataURL(file.files[0]);
    20 
    21         }

    2、文件发送后台

    js代码:发送数据到后台

     1  /**提交请求到后台,将文件对象作为json字符串发送*/
     2         var image='';
     3         function uploadImage() {
     4             var data = {value:image};
     5             alert(image);
     6             $.ajax({
     7                 type:'POST',
     8                 url:'/login/ModifyImage',
     9                 contentType:'application/json;charset=utf-8',
    10                 data:JSON.stringify(data),//json字符串格式发送
    11                 dataType:'json',
    12                 success:function (result) {
    13             readImg(result);
    14                     alert("成功");
    15                 }
    16             });
    17         }

    3、java后台接收数据

    思路:前台传以data:image/jpeg;base64,开头的base64编码的String字符串,后台接收字符串以后先进行base64解码 .decodeBuffer(),转换成二进制编码,然后使用字节输出流FileOutputStream()将文件保存到指定目录下。 

    /**实现上传图片功能*/
        @RequestMapping(value = "/ModifyImage",method = RequestMethod.POST)
        @ResponseBody
        public String changeImage(@RequestBody String data) throws IOException {
            /**将json字符串转成json对象*/
            JSONObject jsonObject = JSONObject.fromObject(data);
            /**获取文件的头部分*/
            String header = "data:image/jepg;base64,";
            /**获取文件的实体部分*/
            String image = jsonObject.getString("value");
            System.out.println(image.length());
            /**剪切头部分*/
            image = image.substring(header.length());
            BASE64Decoder decoder = new BASE64Decoder();
                /**用base64解码,decodeBuffer()转成二进制编码*/
                byte[] bytes = decoder.decodeBuffer(image);
                long time = System.currentTimeMillis();
                /**指定保存的路径*/
    
                String str = LoginController.class.getPackage().toString();
                System.out.println(str);
                File path = new File("F:/temp/"+time+".jpg");
                System.out.println(path);
                FileOutputStream outputStream = new FileOutputStream(path);
                outputStream.write(bytes);
                outputStream.close();
    
            return path.getAbsolutePath();
        }

    4、后台处理请求

     1   /**服务器向浏览器发送图片*/
     2     @RequestMapping(value = "/getImage",method = RequestMethod.POST)
     3     @ResponseBody
     4     public String sendImg(@RequestBody String path) throws IOException {
     5         JSONObject jsonObject = JSONObject.fromObject(path);
     6         /**获取文件的路径*/
     7         String paths = jsonObject.get("value").toString();
     8         File file = new File(paths);
     9         /**读取图片*/
    10         BufferedImage image = ImageIO.read(file);
    11         ByteArrayOutputStream out = new ByteArrayOutputStream();
    12         ImageIO.write(image,"jpg",out);
    13         /**将当前输出流转为字节数组*/
    14         byte[] data = out.toByteArray();
    15         BASE64Encoder encoder = new BASE64Encoder();
    16         /**对字节数组进行编码*/
    17         String imageString = encoder.encodeBuffer(data).trim();
    18         imageString.replaceAll("
    ","").replaceAll("
    ","");
    19         return imageString;
    20     }

    5、前端页面显示图片

     $("#myImg").attr("src","data:image/jpg;base64,"+res);
    注意:data:image/jpg;base64,为Base64编码的头
     1      /**接收服务器发送过来的图片*/
     2         function readImg(result) {
     3             var data = {value:result};
     4             $.ajax({
     5                 type:'POST',
     6                 url:'/login/getImage',
     7                 contentType:'application/json;charset=utf-8',
     8                 data:JSON.stringify(data),//json字符串格式发送
     9                 dataType:'text',
    10                 success:function (res) {
    11                     alert(res);
    12                     $("#myImg").attr("src","data:image/jpg;base64,"+res);13                 }
    14             });
  • 相关阅读:
    智能交通监控
    YOLOV4知识点分析(二)
    YOLOV4知识点分析(一)
    错误日志写入到本地磁盘(lock 队列)
    $.each(data, function (index, value) { })的用法;json和list<>的互相转换
    ArraySegment 的使用 【转载】
    Ajax往后台传参数,无参数,一个参数,多个参数,一个对象等
    在gridview里查找模板里的button控件
    数据可视化之PowerQuery篇(十六)使用Power BI进行流失客户分析
    数据可视化之PowerQuery篇(十五)如何使用Power BI计算新客户数量?
  • 原文地址:https://www.cnblogs.com/xiaocao123/p/9529160.html
Copyright © 2020-2023  润新知