• 上传文件复用代码【fileUpload】


    这是使用了FileUpload上传组件的,解决了中文乱码问题了,并且删除了临时文件的。

    • 使用了一个Book对象做示范
    private Book uploadData(HttpServletRequest request) {
    
            Book book = new Book();
            try{
    
                //1.得到解析器工厂
                DiskFileItemFactory factory = new DiskFileItemFactory();
    
                //2.得到解析器
                ServletFileUpload upload = new ServletFileUpload(factory);
    
                //设置编码
                upload.setHeaderEncoding("UTF-8");
    
    
                //为上传表单,则调用解析器解析上传数据
                List<FileItem> list = upload.parseRequest(request);  //FileItem
    
                //遍历list,得到用于封装第一个上传输入项数据fileItem对象
                for(FileItem item : list){
    
                    if(item.isFormField()){
    
                        //得到的是普通输入项
                        String name = item.getFieldName();  //得到输入项的名称
                        String value = item.getString("UTF-8");
    
                        //使用BeanUtils封装数据
                        BeanUtils.setProperty(book, name, value);
                    }else{
    
                        //得到上传输入项
    
                        //得到上传文件名全路径
                        String filename = item.getName();
    
                        //截取文件名
                        filename = filename.substring(filename.lastIndexOf("\")+1);
    
                        InputStream in = item.getInputStream();   //得到上传数据
    
                        int len = 0;
                        byte buffer[]= new byte[1024];
    
                        //如果没有这个目录,就创建它
                        String savepath = this.getServletContext().getRealPath("/image");
                        File file = new File(savepath);
                        if (!file.exists()) {
                            file.mkdir();
                        }
    
                        FileOutputStream out = new FileOutputStream(savepath + "\" + filename);
                        while((len=in.read(buffer))>0){
                            out.write(buffer, 0, len);
                        }
                        //设置图片的名字
                        book.setImage(filename);
    
                        in.close();
                        out.close();
    
                        //关闭临时文件
                        item.delete();
    
                    }
                }
    
            }catch (Exception e) {
                e.printStackTrace();
            }
            return book;
        }
    如果您觉得这篇文章帮助到了您,可以给作者一点鼓励



  • 相关阅读:
    分布式-通信(NIO&BIO&网络模型&零拷贝)
    cmake构建和链接静态库与动态库
    ldd
    CMAKE_BUILD_TYPE
    C/CXX attribute
    ffmpeg使用说明(2):ffmpeg提取video,audio,yuv/rgb,PCM
    ffmpeg使用说明(1):ffmpeg帮助使用指南
    ffmpeg使用说明(0):ffmpeg/ffplay/ffprobe
    ffplay使用帮助说明
    书写log的艺术
  • 原文地址:https://www.cnblogs.com/zhong-fucheng/p/7203007.html
Copyright © 2020-2023  润新知