zoukankan      html  css  js  c++  java
  • java web开发 图片上传功能

    基本思路在于,配置路径,然后用java I/O的api将图片上传到该目录下。

    String photoPath =
       ServletActionContext.getServletContext().getRealPath("/user/photo/" + username);

    这句是获取服务器下的目录+username

    而username通过session获取。

    这是一个图片上传action的方法:

        public String execute() throws Exception {
            //获得username
            Map session = ServletActionContext.getContext().getSession();
            String username = (String) session.get("username");
            
            //创建一个输入流
            InputStream is = new FileInputStream(myFile);
            //设置文件保存目录
            String photoPath = 
                ServletActionContext.getServletContext().getRealPath("/user/photo/" + username);
            File filePhotoPath = new File(photoPath);
            if(!filePhotoPath.isDirectory()) {
                filePhotoPath.mkdir();
            }
            
            //解决中文文件名问题
            String extension = FilenameUtils.getExtension(this.getMyFileFileName());
            String filename = UUID.randomUUID().toString() + "."+ extension;
            
            //设置目标文件
            File tofile = new File(photoPath,filename);
            //使用输出流来包装目标文件
            OutputStream os = new FileOutputStream(tofile);
            byte[] buffer = new byte[1024];
            int length = 0;
            while((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            //关闭输入流
            is.close();
            //关闭输出流
            os.close();
            
            return this.SUCCESS;
        }
  • 相关阅读:
    Android 摇一摇之双甩功能
    Android 上千张图片的列表滑动加载
    Android 新手引导
    Android 自定义列表指示器
    Mininet的安装与卸载
    ubuntu装机必备
    linux系统中利用vagrant创建虚拟开发环境
    Ubuntu右键添加:open in terminal
    ryu启动问题总结
    新建WORD文档打开会出现转换文件对话框3步解决办法
  • 原文地址:https://www.cnblogs.com/rixiang/p/5254355.html
Copyright © 2011-2022 走看看