JAVA upload image function

                The front-end and back-end realize the function of uploading pictures (JAVA code)

1. Front end probably

The request header must be an AJAX request header: 'X-Requested-With': 'XMLHttpRequest'

It generally refers to the Content-Type that exists in the web page, which is used to define the type of network file and the encoding of the web page, and decide what form the file recipient will be in:
                                                  application/x-www-form-urlencoded: The data is encoded as a name/value pair. This is the standard encoding format.
                                                  multipart/form-data: The data is encoded as a message, and each control on the page corresponds to a part of the message.

 

2. Set the request header format

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

3. AJAX request code:

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) ; //Single picture, multiple add                 console.log(param)
                with loop append                }else{                   this.$message.error("The picture is wrong" );                   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 background code (comparatively long: the reason is a method, for the convenience of everyone to see)

    @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;//Define the name for the picture
        String imgPath = null;//The upload path specified for the picture
        String strusercode=null;
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        try{
            //Create a server path to store pictures
            imgPath=THESERVERURL+"broadcast\\";
            //Create a folder
            File file = new File(imgPath);
            if (!file.exists()){// create a folder
                file.mkdirs();
            }else{
                //delete all pictures in the file
                String name[]=file.list();
                for (int i=0; i<name.length; i++){  
                    File f=new File(imgPath,name[i]);//The file in the folder  
                    f.delete();//Delete the file  
                }  
            }
            DiskFileItemFactory factory = new DiskFileItemFactory(); // set the factory
            factory.setRepository(new File(imgPath)); // set the file storage location
            factory.setSizeThreshold(1024 * 1024); // set the size, if the file is smaller than the set size, put it into memory , if it is larger than it, put it on the disk, the unit is byte
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8"); // Here is the code for Chinese file name processing, in fact, there is only one line
            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>();
                    // Judging whether the form data is a normal field or not, it is a picture field
                    if (fileItem.isFormField()){
                        String fieldName = fileItem.getFieldName();// Get the form field name
                        String value = fileItem.getString("utf-8");// Get the form field value
                        strusercode=value;// get user code
                    }else{
                        // Save the uploaded image
                        String value = fileItem.getName();//Value
                        //String fieldName = fileItem.getFieldName();// Get the form field name
                        if(value!=null && !"".equals (value)){
                            // saved image name currentTimeMillis time rub
                            imgName = System.currentTimeMillis()+ fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                            // save(write)
                            fileItem.write(new File(imgPath, imgName));
                            map.put("broadcastUrl", "broadcast/" + imgName);//image path
                            map.put("booleans", "1");//Whether to display pictures
                            map.put("sort", sort);//Picture path
                            map.put("dtnoticetime", PublicTools.gettime());//Upload time
                            list.add(map);
                        }
                    }
                }
                //Delete in the table Picture record
                userDaoImpl.delete("delete from t_broadcast");
                //Insert data into the table
                userDaoImpl.insertinto(BroadcastSql.insertSql(list, strusercode));
            }else{
                return this.returnError(resultJson,ResMessage.Server_Abnormal.code, request);
            }
        } catch (Exception e){
            logger.info("Login information exception",e);
            return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);
        }
        return this.response(resultJson, request);
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324901539&siteId=291194637