图片上传代码


public static String imageUpdate(MultipartFile multfile, HttpServletRequest request,String pathName){
        if (!multfile.isEmpty()) {
            CommonsMultipartFile commonsmultipartfile = (CommonsMultipartFile) multfile;
            DiskFileItem diskFileItem = (DiskFileItem) commonsmultipartfile.getFileItem();
            File file = diskFileItem.getStoreLocation();
            String fileName = System.nanoTime() + multfile.getOriginalFilename();

            String path = Global.getUserfilesBaseDir() + "/userfiles/"+pathName+"/";
            try{
                File newFile = new File(path);
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }

                newFile=new File(path+fileName);
                newFile.createNewFile();
                OutputStream os = null;
                byte[] bs = new byte[1024];
                int len;
                if (!file.exists()) {
                    file.mkdirs();
                }
                InputStream in = null;
                try {
                    in = new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                os = new FileOutputStream(newFile);
                while ((len = in.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                file.delete();
                os.close();
                in.close();
            }catch (Exception e){
                e.printStackTrace();
                return "";
            }
            String url = "http://" + request.getServerName() //服务器地址
                    + ":"
                    + request.getServerPort()           //端口号
                    + "/userfiles/" + pathName + "/";//项目名称
            return url+fileName;
        }
        return "";
    }

 

posted @ 2018-10-16 14:44  冰逸101  阅读(256)  评论(0编辑  收藏  举报