zoukankan      html  css  js  c++  java
  • SSH,SSM框架文件上传

    一、了解文件上传

    1.1        什么是文件上传

    将本地文件通过流的形式写到服务器上

    1.2        文件上传的技术

    • JspSmartUpload: 其组件是应用jsp进行B/S程序开发过程中经常使用的上传文件组件,支持中文文件名文件
    • Fileupload组件(经常):是Apache commons下面的子项目,用来实现java环境下面的文件上传功能
    • Servlet3.0支持:

         文件上传

         注解开发

        异步请求

    • Struts2框架:底层实现了fileupload,对fileupload进行了封装。
    • SpringMvc框架:底层也实现了文件的上传

    1.3        文件上传要素

    • 表单的提交方式必须是Post
    • 表单中需要提供<input type=”file”>这个文件项必须有name属性值
    • 表单的enctype属性必须设置为multipart/form-data

    2         文件上传代码实现

    2.1        修改jsp页面

    • 提供文件上传项

     

    2.2        修改表单的enctype属性:

     

    3. 目录分离算法分析:

           

    二、SSH中struts2的文件上传;

       1. action 里面的设置:

    @Controller
    @Scope("prototype")
    public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
        @Autowired
        private CustomerService customerService;
        // 模型驱动使用的对象
        private Customer customer = new Customer();/**
         * 文件上传提供的三个属性,需要添加set方法,这三个属性必须要有属性驱动注入
         */
        private String uploadFileName;//接收文件上传的名称
        private File upload;//要上传的文件,这个名称要跟jsp页面的文件上传组件的name属性值一样
        private String uploadContentType;//文件类型
        
        public void setUploadFileName(String uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
        public void setUpload(File upload) {
            this.upload = upload;
        }
        public void setUploadContentType(String uploadContentType) {
            this.uploadContentType = uploadContentType;
        }
        @Override
        public Customer getModel() {
            return customer;
        }/**
         * 保存客户信息
         * <p>Title: CustomerAction</p>
         * <p>Description: </p>
         * @return
         * @throws IOException 
         */
        public String saveCustomer() throws IOException {
            //上传文件:
            if(upload != null) {
                //设置文件上传路径
                String path = "C:/upload";
                //一个目录下存放的相同文件名:随机文件名
                String uuidFileName = UploadUtils.getUUIDFleName(uploadFileName);
                //一个目录下存放的文件过多:目录分离
                String realPath = UploadUtils.getPathByHash(uuidFileName);
                //创建目录
                String url = path + realPath;
                File file = new File(url);
                if(!file.exists()) {
                    file.mkdirs();
                }
                //文件上传
                File dictFile = new File(url + "/" + uuidFileName);
                FileUtils.copyFile(upload, dictFile);
            }
            customerService.saveCustomer(customer);
            return NONE;
        }
    }

     2. 编写文件目录工具类

    package com.sshcrm.utils;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * 文件上传工具类
     * <p>
     * Title: UploadUtils.java
     * </p>
     * <p>
     * Description:
     * </p>
     * <p>
     * Company: WSJT
     * </p>
     * 
     * @author 王亚强
     * @date 2018年7月26日
     *
     */
    public class UploadUtils {
        public static String getUUIDFleName(String fileName) {
            // 获取唯一的文件名加上扩展名
            String extions = fileName.substring(fileName.lastIndexOf("."));
            String uuidFileName = IdGenertor.genGUID() + extions;
            return uuidFileName;
        }
    
        // 目录分离法来获取目录
        public static String getPathByHash(String uuidFileName) {
            // 目录分离
            int code1 = uuidFileName.hashCode();
            int d1 = code1 & 0xf;// 作为一级目录
            int code2 = code1 >>> 4;// 右移4位
            int d2 = code2 & 0xf;// 作为二级目录 0x代表16进制
            return "/" + d1 + "/" + d2;
        }
    
        // 日期目录分离法
        public static String getPathByDate() {
            // 目录分离
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");
            String timePath = simpleDateFormat.format(date);
            return timePath;
        }
    }
    package com.sshcrm.utils;
    
    import java.math.BigInteger;
    
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Random;
    import java.util.UUID;
    /**
     * 获取GUID和UUID
     * @author Mike
     *
     */
    public class IdGenertor {
        private static UUID uuid=null;
        private static final Random RANDOM=new Random();
        //获取UUID
        public static String getUUID() {  
            uuid = UUID.randomUUID();   
            String idstr = uuid.toString().replace("-", "");  
            return idstr.toUpperCase();  
        }  
        //获取GUID
        public static String genGUID(){
            return new BigInteger(165, RANDOM).toString(36).toUpperCase();
        }
        
        public static String genOrdernum(){
            Date now = new Date();
            DateFormat df = new SimpleDateFormat("yyyyMMdd");
            String s1 = df.format(now);// 20141026+纳秒
            return s1+System.nanoTime();
        }
    }

    3.struts设置文件上传限定:workflow是struts最后一个拦截器,如果其中拦截器没有通过并且没有设置input视图就会跳转到没有视图的页面

    4. 配置好在跳转页面回显错误信息

    三、SSM框架springMVC文件上传:

    1. 需要在Controller方法参数类添加MutipartFile uploadFile;注意uploadFile要与jsp页面的属性名字一样

        @RequestMapping(value="/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE + ";charset=utf-8")
        @ResponseBody
        public String pictureUpload(MultipartFile uploadFile){
            Map<String, Object> result = pictureService.uploadPicture(uploadFile);
            //为了保证功能的兼容性,需要把Result转化为json格式的字符串
            String json = JsonUtils.objectToJson(result);
            return json;
        }

    2. pictureService代码:

    @Override
        public Map uploadPicture(MultipartFile uploadFile){
            Map<String,Object> resultMap = new HashMap<>();
            try {
                //生成一个新的文件名
                //取原始文件名
                String oldFileName = uploadFile.getOriginalFilename();
                //生成新文件名
            //设置文件上传路径
                String path = "C:/upload";
                //一个目录下存放的相同文件名:随机文件名
                String uuidFileName = UploadUtils.getUUIDFleName(uploadFileName);
                //一个目录下存放的文件过多:目录分离
                String realPath = UploadUtils.getPathByHash(uuidFileName);
                //创建目录
                String url = path + realPath;
                File file = new File(url);
                if(!file.exists()) {
                    file.mkdirs();
                }
                //文件上传
                File dictFile = new File(url + "/" + uuidFileName);
                FileUtils.copyFile(upload, dictFile);
           resultMap.put("error", 0); 
           resultMap.put(
    "url",url + "/" + uuidFileName);
           return resultMap;
         } catch (IOException e) { 
          resultMap.put(
    "error", 1);
          resultMap.put(
    "message", "文件上传发送异常");
          return resultMap;
        }
    }
  • 相关阅读:
    09_ssh服务器的安装和使用
    08_linux下的文件压缩和解压
    38-自定义异常类
    37-手动抛出异常对象
    DataGrip 2020.1 安装与激活
    36-异常的处理
    35-异常
    node+ajax实战案例(1)
    ajax前后端交互原理(7)
    ajax前后端交互原理(5)
  • 原文地址:https://www.cnblogs.com/ya-qiang/p/9369963.html
Copyright © 2011-2022 走看看