码迷,mamicode.com
首页 > Web开发 > 详细

图片上传代码

时间:2018-10-16 15:51:14      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:original   span   puts   update   stream   return   base   except   string   


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 "";
    }

 

图片上传代码

标签:original   span   puts   update   stream   return   base   except   string   

原文地址:https://www.cnblogs.com/-strong/p/9718296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!