首页 > 其他分享 >上传文件到服务器

上传文件到服务器

时间:2023-10-23 20:35:52浏览次数:47  
标签:文件 String businessTable request entity new 服务器 上传 concat

上传附件至linux服务器:
controller层:

点击查看代码
@Override
    public Result<?> uploadFile(MultipartHttpServletRequest request,
                                @RequestParam(value = "businessTable") String businessTable,
                                @RequestParam(value = "businessId") String businessId,
                                @RequestParam(value = "businessIds[]", required = false) List<String> businessIds) {

        List<AttachmentFileDto> filesInfo = null;
        if (StringUtils.isBlank(businessTable))
            throw new ControllerException(SimpleErrorCode.ParamsError);
        if (CollectionUtils.isNotEmpty(businessIds)) {
            //一个文件对应多业务主键
            filesInfo = FileUtil.writeManyBusinessFileIntoDisk(request, businessTable, businessIds);
        } else if (StringUtils.isNotBlank(businessId) || "T_XTGL_FJ".equals(businessTable)) {
            //一个文件对应一个业务主键 上传至文件系统
//            filesInfo = FileUtil.writeBusinessFileIntoDisk(request, businessTable, businessId);
            filesInfo = FileUtil.uploadFileByFastDFS(request, businessTable, businessId,fastFileStorageClient);
        } else {
            throw new ControllerException(SimpleErrorCode.ParamsError);
        }
        return Result.buildSuccessResult(filesInfo);
    }

工具类:

点击查看代码


    // 单个文件最大允许上传大小50MB
    private static final long MAX_SINGLE_FILE_SIZE = 52428800;

    // 基础设置的附件根目录
    private static String attachmentBasePath;
    // 附件表Mapper
    private static AttachmentFileMapper attachmentFileMapper;
    // 当前服务名
    private static String applicationName;

    @Value("${spring.application.name}")
    public void setapplicationName(String name) {
        applicationName = name;
    }
	
	 /**
     * 获取全局设置的附件根目录
     *
     * @return
     */
    public static String getAttachmentBasePath() {
        attachmentBasePath = attachmentFileMapper.getSysAttachmentFileRootPath();
        attachmentBasePath = StringUtils.isNotBlank(attachmentBasePath) ? attachmentBasePath
                : File.separator.concat("higherVocationEduFile").concat(File.separator).concat("attachmentFile");
        return attachmentBasePath;
    }
	
/**
     * 上传业务附件方法(单个文件对应多个业务主键时调用)
     *
     * @param request       @NotNull
     * @param businessTable 业务主表
     * @param businessIds   业务主键
     * @return
     */
    public static List<AttachmentFileDto> writeManyBusinessFileIntoDisk(MultipartHttpServletRequest request,
                                                                        String businessTable, List<String> businessIds) {
        SystemUserInfo systemUserInfo = SessionUtil.getSystemUserInfo(request);
        if (systemUserInfo == null) {
            throw new ServiceException(SimpleErrorCode.UserNotLogin);
        }
        // isOverrideAdd 是否覆盖追加(override:覆盖,原有文件将清除,add :追加原有文件保留并追加)
        if ("override".equals(request.getParameter("isOverrideAdd"))) {
            // 删除硬盘中的文件
            List<String> fileIds = deleteBusinessFile(businessTable, businessIds);
        }
        Date currentDate = new Date();
        StringBuffer stringBuffer = new StringBuffer();
        List<AttachmentFileDto> list = new ArrayList<>();
        AttachmentFileDto entity = null;
        MultipartFile file = null;
        FileOutputStream out = null;
        Iterator<String> itFiles = request.getFileNames();
        int i = 0;
        while (itFiles.hasNext()) {
            i++;
            file = request.getFile(itFiles.next());
            try {
                // 获取文件名
                String fileName = request.getParameter("fileName");
                String fileUid = request.getParameter("fileUid");
                String reFileName = fileName;
                long size = file.getSize();
                if (size == 0) {
                    throw new IOException("文件《" + fileName + "》为空");
                } else if (size > MAX_SINGLE_FILE_SIZE) {
                    throw new ServiceException(SimpleErrorCode.SaveFailure.getErrorCode(), "文件《" + fileName + "》太大");
                }
                // 文件类型
                String contentType = file.getContentType();
                contentType = StringUtils.isBlank(contentType) ? request.getParameter("fileType") : contentType;
                for (int j = 0; j < businessIds.size(); j++) {
                    if (j > 0) {
                        reFileName = FilenameUtils.getBaseName(fileName).concat("(" + j + ").")
                                .concat(FilenameUtils.getExtension(fileName));
                    }
                    // 设置文件存储相对路径(服务名/日期/文件名-文件id)
                    String relativePath = applicationName.concat(File.separator).concat(DateUtils.getDate())
                            .concat(File.separator).concat(fileUid).concat("-").concat(reFileName);
                    // 设置文件存储路径(全局根路径/相对路径)
                    String filePath = FilenameUtils
                            .normalize(getAttachmentBasePath().concat(File.separator).concat(relativePath));

                    File dest = new File(filePath);
                    // 检测是否存在目录
                    if (!dest.getParentFile().exists()) {
                        // 新建文件夹
                        dest.getParentFile().mkdirs();
                    }
                    log.info("文件保存路径{}", dest.getAbsolutePath());
                    out = new FileOutputStream(dest);
                    String businessId = businessIds.get(j);
                    IOUtils.copy(file.getInputStream(), out);

                    entity = new AttachmentFileDto();
                    entity.setRelationalId(uuidStringGenerator.nextUUID());
                    entity.setUid(fileUid);
                    entity.setName(fileName);
                    entity.setFilePath(filePath);
                    entity.setSize((double) size);
                    entity.setType(contentType);
                    entity.setBusinessId(businessId);// 业务主键
                    entity.setBusinessTable(businessTable);
                    entity.setService(applicationName);// 服务名
                    entity.setIsCanbeDownload("1");// 是否可下载
                    entity.setClientIp(IpUtils.getIp());
                    entity.setCreateTime(currentDate);
                    entity.setCreator(systemUserInfo.getUserId());
                    entity.setCreatorName(systemUserInfo.getName());
                    entity.setEditTime(currentDate);
                    entity.setEditor(systemUserInfo.getUserId());
                    entity.setEditorName(systemUserInfo.getName());
                    entity.setSchoolCode(systemUserInfo.getSchoolCode());
                    entity.setSchoolName(systemUserInfo.getSchoolName());
                    list.add(entity);
                }

            } catch (IOException e) {
                log.error("第 " + i + " 个文件上传失败 ==> ", e);
                stringBuffer.append("第 " + i + " 个文件上传失败 ==> " + e.getMessage());
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        log.info("附件表数据{}", list);
        if (stringBuffer.length() > 0) {
            throw new ServiceException(001, stringBuffer.toString());
        }
        // 记录文件信息到数据库
        attachmentFileMapper.batchInsert(list);
        return list;
    }

标签:文件,String,businessTable,request,entity,new,服务器,上传,concat
From: https://www.cnblogs.com/heavenTang/p/17783393.html

相关文章

  • 文件stm32f4xx.h 解析
    本文简短不看版:这个是头文件的头文件这个文件是个头文件,它又包含了两个头文件(通过在Keil魔法棒工具定义两个宏STM32F407xx和USE_HAL_DRIVER 开关)#include"stm32f407.h" //某一特定F4型号芯片寄存器定义#include"stm32f4xx_hal.h"//HAL库函数(HAL库编程的API总集合)......
  • 使用Git版本控制查看文件的更改历史
    内容来自DOChttps://q.houxu6.top/?s=使用Git版本控制查看文件的更改历史如何查看单个文件的完整更改历史记录?gitlog--[filename]显示了文件的提交历史,但我如何查看更改的文件内容?对于图形视图,请使用gitk:gitk[filename]若要跟踪文件重命名后的文件:gitk--follo......
  • IO流,对象流,将对象序列化到文件中,将对象反序列化到内存中
    一一一、序列化!!一、首先创建一个对象类,实现Serializable标记接口 对象中,实现了接口,三个私有属性,并且创建了无参有参构造,get和set方法和toString方法 (一个标准的对象模型)二、序列化到外部文件 结果: 也是一堆乱码,还是因为用字节输出的原因。 二二二、反序列化! 结......
  • redis 配置文件 - 启动redis 使用文件配置启动
    #Redisconfigurationfileexample.##Notethatinordertoreadtheconfigurationfile,Redismustbe#startedwiththefilepathasfirstargument:##./redis-server/path/to/redis.conf#Noteonunits:whenmemorysizeisneeded,itispos......
  • 怎样将SQL Server数据库迁移到新服务器
    一、在老的服务器上打开SQLServerManagementStudio,输入数据库用户名和密码后登录数据库。二、打开对象资源管理器,打开数据库找到需要迁移的数据库,比如这里的test数据库。三、选中需要迁移的数据库,右键点击数据,打开数据库属性,点击文件,查看并记录数据库的路径,然后关......
  • SpringBoot上传图片到指定目录并回显
    一、概述案例:1.利用SpringBoot写一个后台2.接收前端传递过来的图片并保存到服务器。3.前端可以通过url访问上传过的图片步骤:1.写一个FileController专门用来接收前端提交的图片文件,并把图片保存到服务器的指定位置2.配置W......
  • Selenium4 上传文件,弹出对话框(非input框)
    场景:点击一个按钮,然后弹出对话框,从本地选择需要上传的文件,自动关闭对话框。最后在点击web页面的ok按钮提交上传文件。ps:因为这里是按钮上传,所以用input框的sendkeys方法是无法上传成功的了。下面是点击按钮上传成功的案例,需要注意的是,上传时,还需要了解各个按键是什么text来......
  • java实现文件上传到服务器
    本文实例为大家分享了java实现文件上传到服务器的具体代码,供大家参考,具体内容如下1、运行jar包,发送post请求publicstaticvoidmain(String[]args){    //StringfilePath="C:/Users/706293/IT_onDuty.xls";    StringfilePath=args[0];    String......
  • AntDesignVue 通过点击确定按钮实现文件上传
    示例图相关代码<template><div><a-modalv-model:visible="props.uploadVisible"width="1300px":footer="null"maskClosable@......
  • [侯捷_C++面向对象高级开发_上] 2 头文件和类的声明
    1.CvsC++关于数据和函数CDataFunctions对于C来说,数据大部分情况是所有函数都可以访问的,这样对程序来说会变得很混乱C++DataMembersMemberFunctions对于C++来说,数据和函数封装在一起形成类,可以设定为数据只能让类里的函数访问,具有良好的组织性2.C++关于数......