文件的上传,下载,预览


文件上传需要用到:ajaxfileupload.js

页面:

<a class="orange upload-work-confirm" data-id="upload_file1" data-candidateid="${candidateId!''}" data-jobid="${jobId!''}" href="javascript:void(0);"> 
	<i class="icon-all recom-uploading-icon"></i>
	<label class="modalupl">上传文件
	<span style="white-space:pre">	</span><input type="file" class="upload" id="upload_file1" name="offerUpload">
	</label>
</a>


js:

//  文件上传
	$(".upload-work-confirm").on('change', function() {
		var candidateId = $(this).attr("data-candidateid");
		var jobId = $(this).attr("data-jobid");
		var id = $(this).attr("data-id");
		$.ajaxFileUpload({
			url : base + "/gwFile/toGwUpload.htm",
			data : {
				candidateId : candidateId
			},
			secureuri : false,
			fileElementId : id,
			dataType : 'json',
			success : function(data) {
				if (data.success == 0) {
					$.ajax({
						url : base + "/gwCandidate/saveUploadWork.htm",
						data : {
							candidateId : candidateId,
							jobId : jobId
						},
						type : "POST",
						dataType : "json",
						success : function(data) {
							if (data.success == 0) {
								alert("上传成功");
							} else {
								alert("系统异常,请稍后再试");
							}
						}
					});
				} else if (data.success == 2) {
					globalLogin(data.msg);
					return false;
				} else {
					alert(data.errorMsg);
				}
			}
		});
	});


java后台:

/**
     * 获取对应上传的文件
     * 
     * @return
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/toGwUpload")
    @ResponseBody
    @NeedPermission(true)
    @NeedLogin(true)
    public ResponseEntity<Map<String, Object>> toUpload(HttpServletRequest request, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put("msg", "");
            GwAccountBean gwInfo = (GwAccountBean) request.getSession().getAttribute("gwInfo");
            if (null == gwInfo) {
                LOGGER.debug("GW  没有的登录,跳转到登录页面");
                map.put("success", 2);
                map.put("msg", "gw");
                map.put("code", 2);
                return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
            }

            // 保存上传的文件
            MultipartHttpServletRequest multipartHttpservletRequest = (MultipartHttpServletRequest) request;
            // MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // MultipartHttpServletRequest multipartHttpservletRequest = resolver.resolveMultipart(request);
            for (Iterator it = multipartHttpservletRequest.getFileNames(); it.hasNext();) {
                String key = (String) it.next();
                MultipartFile multipartFile = multipartHttpservletRequest.getFile(key);
                if (multipartFile == null) {
                    map.put("success", 3);
                    map.put("errorMsg", "文件上传异常,请稍后重试");
                    map.put("code", 1);
                    return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
                }
                String html = "";// 转换的html路径与名称
                String fileName = multipartFile.getOriginalFilename();// 文件名称
                if (!StringUtils.isEmpty(fileName)) {
                    //去掉文件名中的所有空格
                    fileName = fileName.replaceAll(" ", "");
                }
                String last = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                List<String> arrowExtension = Arrays.asList(".xls,.xlsx,.doc,.docx,.pdf".split(","));
                if (!arrowExtension.contains(last.toLowerCase())) {
                    map.put("success", 4);
                    map.put("errorMsg", "不能上传该格式的文档");
                    map.put("code", 1);
                    return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
                }
                map.put("fileName", fileName);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String date = sdf.format(new Date());
                String path = lieniProperties.getLocalFilePath() + File.separatorChar + date;
                String picPath = path + File.separatorChar;// 文件保存路径
                String filePath = (String) session.getAttribute("filepath");// 文件上传保存的路径
                if (StringUtils.isNotBlank(filePath)) {// 上传过
                    String filePathLast = filePath.substring(filePath.lastIndexOf("."), filePath.length());
                    if (!filePathLast.equals(last)) {
                        CommonUtil.deleteFile(filePath, null);
                        filePath = filePath.replace(filePathLast, last);
                    }
                    fileName = filePath.substring(filePath.lastIndexOf(File.separatorChar), filePath.length());
                    html = filePath.substring(0, filePath.lastIndexOf(".")) + ".html";
                    picPath = picPath
                            + filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1,
                                    filePath.lastIndexOf(".")) + File.separatorChar;
                } else {
                    String name = UUID.randomUUID().toString();
                    fileName = name + last;
                    html = path + File.separatorChar + name + ".html";
                    filePath = path + File.separatorChar + fileName;
                    picPath = picPath + name + File.separatorChar;
                }

                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {// 文件保存路径
                    targetFile.mkdirs();
                }
                multipartFile.transferTo(targetFile);

                session.setAttribute("filepath", targetFile.getPath());

                map.put("filepath", targetFile.getPath());
                map.put("htmlpath", html);
                map.put("success", 0);
                map.put("code", 0);
            }

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", 1);
            map.put("code", 0);
            map.put("errorMsg", "系统异常,请稍后重试");

        }
        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
    }
对应的文件存放路径放在了session中,我们可以把对应路径存放在数据库中,如果需要下载或者预览,直接从数据库中读取文件路径


文件下载:


 /**
     * 
     * 文件下载推荐报告
     * 
     * @param request
     * @param downType 1:表示下载推荐报告;2表示下载offer
     * @param session
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/toGwDown")
    @NeedPermission(true)
    @NeedLogin(true)
    public void toDown(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        FileInputStream fis = null;
        OutputStream myout = null;
        BufferedInputStream buff = null;
        try {
            GwAccountBean gwInfo = (GwAccountBean) request.getSession().getAttribute("gwInfo");
            if (null == gwInfo) {
                LOGGER.debug("  没有的登录,跳转到登录页面");
                return;
            }
            String downType = request.getParameter("downType");
            String candidateId = request.getParameter("candidateId");
            String jobId = request.getParameter("jobId");
            if (StringUtils.isBlank(candidateId) || StringUtils.isBlank(jobId) || StringUtils.isBlank(downType)) {
                LOGGER.debug("param is null error");
                return;
            }

            CandidateInfoBean candidateInfoBean = gwOperatorService.queryCandidateInfo(candidateId, gwInfo.getId(),
                    jobId);
            if (null == candidateInfoBean) {
                LOGGER.debug("查询不到对应候选人信息");
                return;
            }
            String fileTypeName = "";
            String filePath = "";
            if ("1".equals(downType)) {
                fileTypeName = "报告" + jobId + "-" + candidateInfoBean.getJobName() + "@" + candidateId + "-"
                        + candidateInfoBean.getCandidateName();
                filePath = candidateInfoBean.getRecommendReportPath();
            } else if ("2".equals(downType)) {
                fileTypeName = "offer" + jobId + candidateInfoBean.getJobName() + "@" + candidateId + "-"
                        + candidateInfoBean.getCandidateName();
                filePath = candidateInfoBean.getOfferAnnexPath();
            } else if ("3".equals(downType)) {
                fileTypeName = "确认函" + jobId + candidateInfoBean.getJobName() + "@" + candidateId + "-"
                        + candidateInfoBean.getCandidateName();
                filePath = candidateInfoBean.getEntryConfirmationPath();
            }

            if (StringUtils.isBlank(filePath)) {
                LOGGER.debug("查询不到对应候选人文件");
                return;
            }
            filePath = properties.getLocalFilePath() + filePath;
            String fileType = filePath.substring(filePath.lastIndexOf("."), filePath.length());
            response.setContentType(CONTENT_TYPE);
            // 得到下载文件的名字
            // String filename=request.getParameter("filename");
            // 解决中文乱码问题
            String filename = new String(filePath.getBytes("iso-8859-1"), "gbk");
            // 创建file对象
            File file = new File(filename);
            // 设置response的编码方式
            response.setContentType("application/x-msdownload");
            // 写明要下载的文件的大小
            response.setContentLength((int) file.length());
            // 设置附加文件名
            // response.setHeader("Content-Disposition","attachment;filename="+filename);

            // 解决中文乱码
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileTypeName + fileType).getBytes("gbk"), "iso-8859-1"));

            // 读出文件到i/o流
            fis = new FileInputStream(file);
            buff = new BufferedInputStream(fis);

            byte[] b = new byte[1024];// 相当于我们的缓存
            long k = 0;// 该值用于计算当前实际下载了多少字节
            // 从response对象中得到输出流,准备下载
            myout = response.getOutputStream();
            // 开始循环下载
            while (k < file.length()) {

                int j = buff.read(b, 0, 1024);
                k += j;

                // 将b中的数据写到客户端的内存
                myout.write(b, 0, j);

            }
            // 将写入到客户端的内存的数据,刷新到磁盘
            myout.flush();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        } finally {
            try {
                if (myout != null) {
                    myout.close();
                }
                if (buff != null) {
                    buff.close();
                }

            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

文件删除:

/**
     * 
     * 删除文件
     * 
     * @param request
     * @param session
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/toGwDelete")
    @ResponseBody
    @NeedPermission(true)
    @NeedLogin(true)
    public ResponseEntity<Map<String, Object>> toDelete(HttpServletRequest request, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put("msg", "");
            GwAccountBean gwInfo = (GwAccountBean) request.getSession().getAttribute("gwInfo");
            if (null == gwInfo) {
                LOGGER.debug("GW  没有的登录,跳转到登录页面");
                map.put("success", 2);
                map.put("msg", "gw");
                map.put("code", 2);
                return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
            }
            // 获取对应文件路径
            String filePath = (String) session.getAttribute("filepath");// 上传保存的路径
            session.removeAttribute("filepath");
           
            String filetype = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
            String htmlPath = filePath.replace(filetype, "html");

            // 删除对应文件
            if (StringUtils.isNotBlank(filePath)) {
                File wordFile = new File(filePath);
                if (wordFile.exists()) {// 文件保存路径
                    if (wordFile.isFile()) { // 为文件时调用删除文件方法
                        wordFile.delete();
                    }

                }
            }
            if (StringUtils.isNotBlank(htmlPath)) {
                File htmlFile = new File(htmlPath);
                String dirPath = htmlPath.substring(0, htmlPath.lastIndexOf("."));
                if (htmlFile.exists()) {// html保存路径
                    if (htmlFile.isFile()) { // 为文件时调用删除文件方法
                        htmlFile.delete();
                    }
                }
                File dirFile = new File(dirPath);
                if (dirFile.exists() && dirFile.isDirectory()) {// 删除对应图片保存目录及文件
                    File[] files = dirFile.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        // 删除子文件
                        if (files[i].isFile()) {
                            files[i].delete();
                        }
                    }
                    dirFile.delete();
                }
            }
            map.put("success", 0);
            map.put("code", 0);

        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", 1);
            map.put("code", 1);
            map.put("errorMsg", "系统异常,请稍后重试");

        }
        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
    }




文件预览可以看另外一篇文章



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值