• JAVA 上传图片功能


                    前后端实现上传图片功能(JAVA代码)

    1.前端大概

    请求头必须为AJAX请求头: 'X-Requested-With': 'XMLHttpRequest'

    一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定文件接收方将以什么形式:
                                                      application/x-www-form-urlencoded:数据被编码为名称/值对。这是标准的编码格式。
                                                      multipart/form-data: 数据被编码为一条消息,页上的每个控件对应消息中的一个部分。

     

    2.设置请求头格式

    Vue.prototype.$sendFormData = axios.create({
      baseURL: baseUrl,
      timeout: 60000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'multipart/form-data'
      },
    })

    3.AJAX请求代码:

    submitUpload() {
                // this.$refs.upload.submit();
                 if(this.imageFileName.length>5){
                    this.$message('图片不能超过5张');
                    return false
               }
                let data  = {};  
                let files = this.imageFileName;  
                console.log(files)
                let param = new FormData(); //创建form对象  
                if(files!=''){  
                    files.forEach((n,i)=>{
                        console.log(n)
                        n['isFormField']=true;
                        param.append('broadcastName',n.raw)
                        // param.append('isFormField',true)
                    })
                    param.append('strusercode',this.pubFuc.user.strusercode)
                    ; //单个图片 ,多个用循环 append 添加   
                    console.log(param)
                }else{  
                    this.$message.error("图片不对");  
                    return false
                }   
                this.$sendFormData.post('broadcast/uploadPicture',param)
                .then(data=>{
                    if(data.data.result==1000){
                        this.imageFileName=[];
                    }else{
                        this.$message({
                            type:"error",
                            message:data.data.msg
                        })
                    }
                })
          },
     

    4.JAVA后台代码(比较长:原因是一个方法,为方便大家看)

        @GET
        @POST
        @Path("/uploadPicture")
        @Produces("application/json;charset=UTF-8")
        @Consumes("multipart/form-data")
        public String uploadPicture(@Context HttpServletRequest request, @Context HttpServletResponse response){
            JSONObject resultJson = new JSONObject();
            String imgName=null;//给图片定义名称
            String imgPath = null;//给图片指定的上传路径
            String strusercode=null;
            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            try{
                //创建服务器路径存储图片
                imgPath=THESERVERURL+"broadcast\";
                //创建文件夹
                File file = new File(imgPath);
                if (!file.exists()){// 创建文件夹
                    file.mkdirs();
                }else{
                    //删除文件中的所有图片
                    String name[]=file.list();
                    for (int i=0; i<name.length; i++){  
                        File f=new File(imgPath,name[i]);//此时就可得到文件夹中的文件  
                        f.delete();//删除文件  
                    }  
                }
                DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置工厂
                factory.setRepository(new File(imgPath)); // 设置文件存储位置
                factory.setSizeThreshold(1024 * 1024); // 设置大小,如果文件小于设置大小的话,放入内存中,如果大于的话则放入磁盘中,单位是byte
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("utf-8"); // 这里就是中文文件名处理的代码,其实只有一行
                List<FileItem> listform = upload.parseRequest(request);
                if (listform != null && !listform.isEmpty()){
                    int sort=0;
                    for (FileItem fileItem : listform){
                        sort++;
                        Map<String,Object> map =new HashMap<String,Object>();
                        // 判断表单数据是否为普通字段 不是则为图片字段
                        if (fileItem.isFormField()){
                            String fieldName = fileItem.getFieldName();// 获取表单字段名称
                            String value = fileItem.getString("utf-8");// 获取表单字段值
                            strusercode=value;//获取用户编码
                        }else{
                            // 上传图片的保存
                            String value = fileItem.getName();//值
                            //String fieldName = fileItem.getFieldName();// 获取表单字段名称
                            if(value!=null && !"".equals(value)){
                                // 保存的图片名称  currentTimeMillis时间搓
                                imgName = System.currentTimeMillis()+ fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                                // 保存(写)
                                fileItem.write(new File(imgPath, imgName));
                                map.put("broadcastUrl", "broadcast/" + imgName);//图片路径
                                map.put("booleans", "1");//是否显示图片
                                map.put("sort", sort);//图片路径
                                map.put("dtnoticetime", PublicTools.gettime());//上传时间
                                list.add(map);
                            }
                        }
                    }
                    //删除表里面的图片记录
                    userDaoImpl.delete("delete from t_broadcast");
                    //往表里插入数据
                    userDaoImpl.insertinto(BroadcastSql.insertSql(list, strusercode));
                }else{
                    return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);
                }
            } catch (Exception e){
                logger.info("登录信息异常",e);
                return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);
            }
            return this.response(resultJson, request);
        }

    周永发
  • 相关阅读:
    spring-boot 速成(6) 整合disconf
    spring-boot 速成(5) profile区分环境
    dubbox REST服务使用fastjson替换jackson
    resteasy经验谈
    spring-boot 速成(4) 自定义配置
    spring-boot 速成(3) actuator
    idea 高级调试技巧
    spring-boot 速成(2) devtools之热部署及LiveReload
    bash编程之xargs实用技巧
    spring-boot 速成(1) helloworld
  • 原文地址:https://www.cnblogs.com/yvanBk/p/8953885.html
Copyright © 2020-2023  润新知