wangeditor图片上传的方法简单实例

js部分

	

java后台代码

 /**
     * 文件上传
     * @param
     * @return
     * @throws IOException 
     */
    @ResponseBody
    @RequestMapping(value = "upload1.do")
    public Result upload2 (@RequestParam(value="myFileName") MultipartFile file) throws IOException {
    	//MultipartFile  转换成文件
        String fileName=file.getOriginalFilename();
        //获取到项目路径
        String savePath = new File("").getCanonicalPath();
        if(file.getSize()>0) {
            try {
                String path = SaveFileFromInputStream(file.getInputStream(), savePath, fileName);
                Map map = new HashMap();
                map.put("imgUrl",path);
                return new Result(map);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(null);
            }
        }else{
            return new Result(null);
        }
    }

    /**保存的
     * @param stream
     * @param savePath
     * @param filename
     * @return
     * @throws IOException
     */
    public String SaveFileFromInputStream(InputStream stream,String savePath,String filename) throws IOException {
        //初始化日期格式
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //以当前日期作加下划线加旧的文件名作为上传文件保存的名称
        String newFileName = sd.format(new Date()) + "_" + filename;
        String savePathAndFileName = savePath + "/"+ newFileName;
        FileOutputStream fs=new FileOutputStream(savePathAndFileName);
        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=stream.read(buffer))!=-1)
        {
            bytesum+=byteread;
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        stream.close();
        return savePathAndFileName;
    }

你可能感兴趣的:(wangEditor)