zoukankan      html  css  js  c++  java
  • 上传与下载

    将网页中的表格导入或者下载到本地,并保存为xls格式

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.XSSFWorkbook;
    
    class DownLoadXls{
        
        //excle生成临时目录
        private String templateDir = "d:/"
    
        //打包成一个方法了
        public void exportUser(HttpServletResponse response){
            List<User> userlist = userService.findAllUser();
            //生成excel,并写入本地和请求的客户端
            Workbook workbook = new XSSFWorkbook();
            workbook.createSheet();
            Sheet sheet0 = workbook.getSheetAt(0);
            Row headRow = sheet0.createRow(0);
            //设置单元格-username
            headRow.createCell(0, Cell.CELL_TYPE_STRING).setCellValue("姓名");
            //设置单元格-password
            headRow.createCell(1, Cell.CELL_TYPE_STRING).setCellValue("密码");
            //设置单元格-birthday
            headRow.createCell(2, Cell.CELL_TYPE_NUMERIC).setCellValue("生日");
            for(int i = 0;i < userlist.size();i++){
                User user = user.get(i);
                Row curRow = sheet0.createRow(i+1);
                curRow.createCell(0,Cell.CELL_TYPE_STRING).setCellValue(user.getUserName());
                curRow.createCell(1,Cell.CELL_TYPE_STRING).setCellValue(user.getPassWord());
                ZoneId zoneId = ZoneId.systemDefault();
                Instant instant = user.getBirthday().atZone(zoneId).toInstant();
                String birthdayTime = DatwTimeUtil.datetimeToStringHH(Date.from(instant));
                curRow.createCell(2,Cell.CELL_TYPE_NUMERIC).setCellValue(birthdayTime);
            }
            BufferedOutputStream out = null;
            try{
                response.reset();
                response.setCharacterEncoding("utf-8");
                //Content-disposition告诉浏览器以下载的形式打开
                //URLEncoder.encode("user.xlsx",StandardCharsets.UTF_8.name());
                response.setHeader("Content-disposition","attachment;filename="+getExportFileName());
                //application/ms-excel;charset=utf-8 告诉浏览器下载的文件是excel
                response.setContentType("application/ms-excel");
                workbook.write(out);
                out.flush();
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                try{
                    out.close();
                }catch(IOException e){
                }
            }
        }
    }

    上传图片,存在数据库中的是图片路径,可以不使用ajax请求,参考:https://www.cnblogs.com/yvanBk/p/8953885.html

    
    

        @GET
        @POST
        @Path("/uploadPicture")
        @Produces("application/json;charset=UTF-8")
        @Consumes("multipart/form-data")
        public String uploadPicture(@Context HttpServletRequest request, @Context HttpServletResponse response){
            JSONObject resultJson = new JSONObject();
            String imgName=null;//给图片定义名称
            String imgPath = null;//给图片指定的上传路径
            String strusercode=null;
            List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
            try{
                //创建服务器路径存储图片
                imgPath=THESERVERURL+"broadcast\";
                //创建文件夹
                File file = new File(imgPath);
                if (!file.exists()){// 创建文件夹
                    file.mkdirs();
                }else{
                    //删除文件中的所有图片
                    String name[]=file.list();
                    for (int i=0; i<name.length; i++){  
                        File f=new File(imgPath,name[i]);//此时就可得到文件夹中的文件  
                        f.delete();//删除文件  
                    }  
                }
                DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置工厂
                factory.setRepository(new File(imgPath)); // 设置文件存储位置
                factory.setSizeThreshold(1024 * 1024); // 设置大小,如果文件小于设置大小的话,放入内存中,如果大于的话则放入磁盘中,单位是byte
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setHeaderEncoding("utf-8"); // 这里就是中文文件名处理的代码,其实只有一行
                List<FileItem> listform = upload.parseRequest(request);
                if (listform != null && !listform.isEmpty()){
                    int sort=0;
                    for (FileItem fileItem : listform){
                        sort++;
                        Map<String,Object> map =new HashMap<String,Object>();
                        // 判断表单数据是否为普通字段 不是则为图片字段
                        if (fileItem.isFormField()){
                            String fieldName = fileItem.getFieldName();// 获取表单字段名称
                            String value = fileItem.getString("utf-8");// 获取表单字段值
                            strusercode=value;//获取用户编码
                        }else{
                            // 上传图片的保存 
                            String value = fileItem.getName();//值
                            //String fieldName = fileItem.getFieldName();// 获取表单字段名称
                            if(value!=null && !"".equals(value)){
                                // 保存的图片名称  currentTimeMillis时间搓
                                imgName = System.currentTimeMillis()+ fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
                                // 保存(写)
                                fileItem.write(new File(imgPath, imgName));
                                map.put("broadcastUrl", "broadcast/" + imgName);//图片路径
                                map.put("booleans", "1");//是否显示图片
                                map.put("sort", sort);//图片路径
                                map.put("dtnoticetime", PublicTools.gettime());//上传时间
                                list.add(map);
                            }
                        }
                    }
                    //删除表里面的图片记录
                    userDaoImpl.delete("delete from t_broadcast");
                    //往表里插入数据
                    userDaoImpl.insertinto(BroadcastSql.insertSql(list, strusercode));
                }else{
                    return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);
                }
            } catch (Exception e){
                logger.info("登录信息异常",e);
                return this.returnError(resultJson,ResMessage.Server_Abnormal.code,request);
            }
            return this.response(resultJson, request);
        }

    
    

    上传视频,参考:https://blog.csdn.net/qq791007/article/details/73332136

    @ResponseBody
    @RequestMapping("upload")
    public Map upload(HttpServletRequest request,
              @RequestParam(value = "myFile", required = false) MultipartFile[] files) { Map map =new HashMap(); try { for(int i=0;i<files.length;i++){ FileUploadUtils.upload(request, files[i]); } map.put("code","1"); map.put("msg","上传成功!"); } catch (Exception e) { map.put("code","0"); map.put("msg","上传失败!"); e.printStackTrace(); } return map; }
    public class FileUploadUtils {
        //默认大小 50M
        public static final long DEFAULT_MAX_SIZE = 52428800;
        //默认上传的地址
        public static  String defaultBaseDir = "upload";
    
        public static final String upload(HttpServletRequest request, MultipartFile file)throws Exception{
            String filename = extractFilename(file, defaultBaseDir);
            File desc = getAbsoluteFile(extractUploadDir(request), filename);
            file.transferTo(desc);
            return filename;
        }
        private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException {
            if(uploadDir.endsWith("/")) {
                uploadDir = uploadDir.substring(0, uploadDir.length() - 1);         }
            if(filename.startsWith("/")) {
                filename = filename.substring(0, uploadDir.length() - 1);        }
            System.out.println(uploadDir + "/" + filename);
            File desc = new File(uploadDir + "/" + filename);
            if(!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();        }
            if(!desc.exists()) {
                desc.createNewFile();        }
            return desc;
        }
    
        public static final String extractFilename(MultipartFile file, String baseDir) throws UnsupportedEncodingException {
            String filename = file.getOriginalFilename();
            int slashIndex = filename.indexOf("/");
            if (slashIndex >= 0) {
                filename = filename.substring(slashIndex + 1);
            }
            filename = baseDir + "/" + filename;
            return filename;
        }
        public static final String extractUploadDir(HttpServletRequest request) {
            return request.getServletContext().getRealPath("/");
        }
    }

    下载视频

    @ResponseBody
    @RequestMapping("getMp4")
    public void getMp4(String cateogry,
                        HttpServletRequest request,
                        HttpServletResponse response) throws IOException {
    
        if(StringUtils.isEmpty(cateogry)) {
            cateogry = "";
        }
        String os = System.getProperty("os.name");
        String path="";
        if(os.toLowerCase().startsWith("win")){
            path="D:/";
        }else{
            path="/home/work/";
        }
    
        String fileName = path+cateogry;
    
        File file = new File(fileName);
    
        //判断文件是否存在如果不存在就返回默认图标
        if(!(file.exists() && file.canRead())) {
            file = new File(path+"company/root.png");
        }
    
        FileInputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[(int)file.length()];
        int length = inputStream.read(data);
        inputStream.close();
        response.setContentType("video/mpeg4");// 设定输出的类型
        response.setHeader("Content-Disposition", "attachment;filename="  + fileName);
    
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
    }
  • 相关阅读:
    《转》12个Sublime Text使用技巧
    Sublime Text 3 快捷键总结
    IIS发布的网站常见的问题汇总
    sublime text 3 安装卸载插件和取消启动检查更新
    sublime text 3 环境变量的配置、安装Package Control、汉化和注册
    github贡献开源项目
    github团队协作
    github desktop的使用
    GitHub网站操作
    HTML中的SVG
  • 原文地址:https://www.cnblogs.com/Fantastic-Code/p/11679101.html
Copyright © 2011-2022 走看看