首页 > Web开发 > 详细

图片上传代码

时间:2018-10-16 15:24:34      阅读:208      评论:0      收藏:0      [点我收藏+]

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

 

图片上传代码

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!