三种上传文件的方式(创建目录方式+数据库方式(集群情况下))--linux下最强版

血泪经验:

在往linux创建文件夹或者目录前首先一定要去命令行或者xftp试下,能不能有没有权限创建,如果命令行都创建不了,那java肯定创建不了,作者就是因为这个吃了亏。
另外如果你的项目是通过docker部署,显示文件创建成功后如果你没有挂载那是看不到的!!!!!!需要先docker exec -it 651118d1f141 /bin/bash。把65这个换成镜像id,先执行这个命令后,就可以看到创建的文件夹了!!!!
方式一:

 //上传文件保存到服务器指定目录
    @Transactional(rollbackFor = Exception.class)
    public Boolean uploadFile(MultipartFile file, Integer orderType) {
        String fileName = file.getOriginalFilename();
        checkFileName(fileName);
        String realPath = dataServiceAddress + orderType.toString();
        File dest = new File(realPath);
        dest.setWritable(true, false);
        dest.setReadable(true, false);
        System.out.println("dest地址" + dest.getAbsolutePath());
        System.out.println("dest是否存在" + dest.exists());
        System.out.println("dest目录:" + dest.isDirectory());
        //文件夹不存在就创建
        if (!dest.exists()) {
            boolean a = dest.mkdirs();
            System.out.println("文件夹创建结果:" + a);
        }
        dest.setWritable(true, false);
        dest.setReadable(true, false);
        try {
            File[] files = dest.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f.isFile()) {
                        f.delete();
                    }
                }
            }
            String filePath = dest.getAbsolutePath() + "/" + fileName;
            File tempFile = new File(filePath);
            if (!tempFile.exists()) {
                tempFile.createNewFile();
                tempFile.setReadable(true, false);
                tempFile.setWritable(true, false);
            }
            file.transferTo(tempFile);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return false;
        }
        return true;
    }

方式二:(有种说法是在linux用java上传文件必须要这种方式,不知道准确性没有测试)

//上传文件保存到服务器指定目录
    @Transactional(rollbackFor = Exception.class)
    public Boolean uploadFile2(MultipartFile file, Integer orderType) {
        try {
            String fileName = file.getOriginalFilename();
            checkFileName(fileName);
            String realPath = dataServiceAddress + orderType.toString() + "/" + fileName;
            File dest = new File(realPath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            Boolean a = dest.getParentFile().setWritable(true, false);
            Boolean b = dest.getParentFile().setReadable(true, false);
            File[] files =  dest.getParentFile().listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f.isFile()) {
                        f.delete();
                    }
                }
            }
            if (!dest.exists()) {
                dest.createNewFile();
            }
            Boolean c = dest.setWritable(true, false);
            Boolean d = dest.setReadable(true, false);
            System.out.println(a.toString() + b.toString() + c.toString() + d.toString());
            InputStream ins = file.getInputStream();
            OutputStream os = new FileOutputStream(dest);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            creditCheckResultExtendMapper.updateDataDocumentStatus(orderType, 1, "userInfoDTO.getLoginName()");
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return false;
        }
        return true;
    }

方式三:在集群情况下,项目被部署到不同的服务器因此上传的文件将会被随机保存到不同的服务器这样就直接jj,所以可以将文件转成二进制文件存储到数据库里这样文件的位置就固定了

 //上传文件保存到服务器指定目录
    @Transactional(rollbackFor = Exception.class)
    public Boolean uploadFile(MultipartFile file, Integer orderType, UserInfoDTO userInfoDTO) {
        try {
            String fileName = file.getOriginalFilename();
            checkFileName(fileName);
            byte[] blob = file.getBytes();
            DataDocumentDTO dataDocumentDTO = toInsertDTO(orderType, userInfoDTO.getLoginName(), blob, fileName);
            creditCheckResultExtendMapper.updateDataDocumentStatus(dataDocumentDTO);
            return true;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return false;
        }
    }

注意这里二进制文件jdbcType要指定为LONGVARBINARY,数据库里的字段要指定为mediumblob

 <update id="updateDataDocumentStatus" parameterType="com.dingxianginc.saasconsole.entity.credit.DataDocumentDTO">
    update dataservice_document
    <set>
      is_upload=#{item.isUpload,jdbcType=INTEGER},
      modify_name=#{item.modifyName,jdbcType=VARCHAR},
      file=#{item.file,jdbcType=LONGVARBINARY},
      file_name=#{item.fileName,jdbcType=VARCHAR},
      last_modify_time=#{item.lastModifyTime,jdbcType=VARCHAR}
    </set>
    where order_type = #{item.orderType}
  </update>
//读取文件
public void downloadDocument(HttpServletResponse response, Integer orderType) throws Exception {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        FileInputStream in = null;
        OutputStream out = null;
        try {
            DataDocumentDTO dataDocumentDTO = creditCheckResultExtendMapper.selectFileByOrderType(orderType);
            byte[] bytes = dataDocumentDTO.getFile();
            String fileName = dataDocumentDTO.getFileName();
            File file;
            String filePath = dataServiceAddress + orderType.toString();
            File dir = new File(filePath);
            if(!dir.exists()){
                boolean result = dir.mkdirs();
                log.info("新建临时目录结果:"+result);
            }
            file = new File(filePath + "/" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            in = new FileInputStream(file);
            if (checkFileName(fileName).equals(".docx")||checkFileName(fileName).equals(".doc")) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/x-msdownload;");
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            if (checkFileName(fileName).equals(".pdf")) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/pdf;");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            }
            out = response.getOutputStream();
            int len;
            byte[] buffer = new byte[10240];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值