Spring中MultipartFile里的临时文件获取

该段代码展示了如何在Spring MVC环境中处理上传的文件。它首先将`HttpServletRequest`转换为`MultipartHttpServletRequest`,然后尝试从`ApplicationPart`获取文件的`location`和`fileItem`字段。获取到的文件信息被打印出来,包括存储位置、绝对路径、文件名和规范化的路径。如果在处理过程中出现IOException、ServletException或IllegalAccessException,文件将被返回。

对于某些缓存文件信息敏感,需反复擦除

 @PostMapping("upload")
    public Object up(HttpServletRequest request){
        Object obj = null;
        File file = null;
        try {
            MultipartHttpServletRequest request1 = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = request1.getFile("file");
            ApplicationPart part = (ApplicationPart)request1.getPart("file");
            Class<?> Clazz = part.getClass();
            Field field;
            if ((field = getField(Clazz, "location")) != null){
                field.setAccessible(true);
                try {
                    obj = field.get(part);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            file = (File) obj;

            if ((field = getField(Clazz, "fileItem")) != null){
                field.setAccessible(true);
                try {
                    obj = field.get(part);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            file = (File) obj;

            DiskFileItem fileItem =(DiskFileItem)obj;

            log.info(fileItem.getStoreLocation().toString());
            log.info(obj.toString());
            log.info(file.getAbsolutePath());
            log.info(file.getName());
            log.info(file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
            return  file;
        } catch (ServletException e) {
            e.printStackTrace();
            return  file;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return  file;
    }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值