• [JavaWeb基础] 009.Struts2 上传文件


    在web开发中,我们经常遇到要把文件上传下载的功能,这篇文章旨在指导大家完成文件上传功能

    1.首先我们需要一个上传文件页面

    <!--在进行文件上传时,表单提交方式一定要是post的方式,
          因为文件上传时二进制文件可能会很大,还有就是enctype属性,
          这个属性一定要写成multipart/form-data,
         不然就会以二进制文本上传到服务器端
    --> 
    <form action="fileUpload.action" method="post" enctype="multipart/form-data">
    	用户名: <input type="text" name="username"><br><br>
            文件:    <input type="file" name="file"><br><br>
    	           <input type="submit" value="提交">
    </form>
    

     2.然后我们要配置Struts2文件

    <action name="fileUpload" class="com.babybus.sdteam.action.FileUploadAction">  
        <result name="success">/Success.jsp</result>     
    </action> 
    

     3.最后我们要有一个Action类把上传的文件转存到服务器

        public String execute() throws Exception
        {
        	// 设置要上传的文件夹目录
            String root = ServletActionContext.getServletContext().getRealPath("/upload");
            // 根据上传的文件,创建输入流
            InputStream is = new FileInputStream(file);
            // 输出文件夹
            File outfloder = new File(root);
            // 输出文件
            File outfile   = new File(root, fileFileName);
            // 目录不存在创建目录
            if(!outfloder.exists()){
            	outfloder.mkdirs();
            }
            // 文件不存在创建文件
            if(!outfile.exists()){
            	outfile.createNewFile();
            }
            // 创建输出流
            OutputStream os = new FileOutputStream(outfile);
            
            // 接受数据用的临时字节数组
            byte[] buffer = new byte[500];
            int length = 0;
            // 遍历把内容写到输出文件中
            while(-1 != (length = is.read(buffer, 0, buffer.length)))
            {
                os.write(buffer);
            }
            // 关闭输出流,关闭输入流
            os.flush();
            os.close();
            is.close();
            // 返回结果跳转标识
            return SUCCESS;
        }
    

     4.通过以上几步,我们就可以简单的实现了文件上传功能。

    结语

    • 受益,掌握了Struts2 上传文件

     

    本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 

    转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4678977.html

  • 相关阅读:
    OpenGL中 Canvas 性能分析
    美颜重磅技术之GPUImage源码分析
    为什么我推荐你用Ubuntu开发?
    使用TensorFlow进行训练识别视频图像中物体
    常用 Git 操作
    JavaScript 禁止表单提交
    AngularJS 解决 SEO 问题
    Linux 命令
    重装Ubuntu系统并配置开发环境
    php开发入门教程
  • 原文地址:https://www.cnblogs.com/superdo/p/4678977.html
Copyright © 2020-2023  润新知