springmvc文件上传

博客提供了文件上传项目的配置相关内容,还给出了源代码的链接,分别为GitHub(https://github.com/pingzhengguo/fileupload)和Gitee(https://gitee.com/BingZhenPingGuo/fileupload)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Component
public class FastDFSClientWrapper {

    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private TestConfig fastDfsValueConfig;      //地址 例如:  http://10.0.91.222:8123/

    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath.getFullPath();
    }

    /**
     * 将一段字符串生成一个文件上传
     *
     * @param content       文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return storePath.getFullPath();
    }

    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = fastDfsValueConfig.getFastdfsAddress() + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 删除文件
     *
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
@Component
public class WorkFlowUpload {
    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;
    @Resource
    private ProcessFastFileMapper processFastFileMapper;
    /**
     * 加载文件服务器的地址
     */
    @Resource
    private TestConfig fastDfsValueConfig;  //地址 例如:  http://10.0.91.222:8123/

    /**
     * 采用springmvc提供的文件上传
     */
    public Map<Integer, ProcessFastFile> workFlowUpload(HttpServletRequest request) throws Exception {

        ProcessFastFile processFastFile = null;
        Map<Integer, ProcessFastFile> processFastFileMap = new HashMap<>();

        //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getSession().getServletContext());

        //检查form中是否有enctype="multipart/form-data"
        if (cmr.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest msr = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = msr.getFileNames();

            while (iter.hasNext()) {
                //一次遍历所有文件
                List<MultipartFile> files = msr.getFiles(iter.next().toString());
                if (files != null) {
                    try {
                        for (MultipartFile file : files) {
                            //得到文件初始的名字
                            String fileOriginalName = file.getOriginalFilename();
                            InputStream inputStream = file.getInputStream();
                            // 取文件格式后缀名
                            String extName = fileOriginalName.substring(fileOriginalName.indexOf(".") + 1);
                            //得到文件在服务器的路径
                            String path = fastDFSClientWrapper.uploadFile(file);
                            //上传
                            file.transferTo(new File(fileOriginalName));
                            Double size = Double.valueOf(file.getSize());
                            processFastFile = new ProcessFastFile();
                            Date timeStamp = Date.from(Instant.now());
                            //把值放到对象里
                            processFastFile.setFileOriginalName(fileOriginalName);
                            processFastFile.setFileOriginalSize(size);
                            processFastFile.setFileServerPath(path);
                            processFastFile.setFileUploadTime(timeStamp);
                            //添加文件信息进fastdfs_file表
                            processFastFileMapper.insert(processFastFile);
                            processFastFile.setFileServerPath(fastDfsValueConfig.getFastdfsAddress() + path);
                            processFastFileMap.put(processFastFile.getId(), processFastFile);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new Exception("文件上传失败");
                    }
                } else {
                    throw new Exception("上传的文件为空");
                }
            }

        }
        return processFastFileMap;
    }

}

 配置:

<!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

 

源代码:
https://github.com/pingzhengguo/fileupload
https://gitee.com/BingZhenPingGuo/fileupload

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值