JAVA后台文件上传接口实现(“.doc“, “.docx“, “.xls“, “.xlsx“, “.pdf“, “.jpg“, “.png“, “.mp4“)

实现文件上传主要依赖Spring的MultipartFile类,MultipartFile是SpringMVC提供简化上传操作的工具类。
  在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类。使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了。
1.Controller.class

/**
 * Created on 2024/3/25.
 */
@RestController
@RequestMapping("/Upload")
public class UploadController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);
    private final String[] sufix = {".doc", ".docx", ".xls", ".xlsx", ".pdf", ".jpg", ".png", ".mp4"};
    @Autowired
    UploadRepository uploadRepository;
    @Value("${local-path}")
    private String localPath;

    // 文件上传、编辑
    @PostMapping("/upload")
    public ResponseObject uploadFile(HttpServletRequest request, @RequestParam MultipartFile files, UploadFile uploadFile) {
        String id = null;
        if(uploadFile.getId() == null){
            id = UUID.randomUUID().toString();
        } else {
            id = uploadFile.getId();
        }

        String year = DateUtil.getCurrentYear();
        FileOutputStream out = null;
        try {
            String fileName = files.getOriginalFilename();
            if (fileName.indexOf("\\") != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\"));
            }
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            // 文件保存路径
            String type = "file";
            String filePath = "";
            uploadFile.setRealName(fileName);
            uploadFile.setId(id);
            uploadFile.setFileName(id + "." + suffix);
            uploadFile.setSuffix(suffix);
            uploadFile.setStatus("0");
            uploadFile.setFileType(FileTypeUtil.getType(suffix).toString());
            uploadFile.setUpDate(DateUtil.getDateTime());
            // uploadFile.setCreateUserId(user.getUserId());
            uploadFile.setCreateTime(DateUtil.getDateTime());
            String relatPath = "";
            if (uploadFile.getFolderName() != null) {
                relatPath = "files/upload/" + year + "/" + type + "/" + uploadFile.getFolderName() + "/";
            } else {
                relatPath = "files/upload/" + year + "/" + type + "/";
            }
            filePath = localPath + relatPath + uploadFile.getFileName();
            uploadFile.setPath(filePath);
            File dest = new File(localPath + relatPath + uploadFile.getFileName());
            uploadFile.setRelatPath(relatPath);
            // 获取文件存放地址
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件保存到指定目录下
            files.transferTo(dest);

            // 文件信息保存到数据库
            uploadRepository.save(uploadFile);

            Map<String, Object> map = new HashMap<>();
            map.put("id", uploadFile.getId());
            map.put("fileType", uploadFile.getFileType());
            map.put("realName", uploadFile.getRealName());
            map.put("path", uploadFile.getRelatPath() + uploadFile.getFileName());
            return ResponseObject.ok("上传成功", map);
        } catch (Exception e) {
            return ResponseObject.error("上传失败");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 文件查询
    @PostMapping("/getFileById")
    public ResponseObject getFileById(@RequestBody UploadFile uploadFile) {
        Optional<UploadFile> file = uploadRepository.findById(uploadFile.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("id", file.get().getId());
        map.put("fileType", file.get().getFileType());
        map.put("realName", file.get().getRealName());
        map.put("path", file.get().getRelatPath() + file.get().getFileName());
        return ResponseObject.ok("文件查询成功", map);
    }

    // 文件删除
    @PostMapping("/delFileById")
    public ResponseObject delFileById(@RequestBody UploadFile uploadFile) {
        Optional<UploadFile> upload = uploadRepository.findById(uploadFile.getId());
        if(upload.isPresent()){
            File file = new File(upload.get().getPath());
            file.delete();
            uploadRepository.deleteById(uploadFile.getId());
            return ResponseObject.ok("文件删除成功!");
        } else {
            return ResponseObject.ok("文件未找到!");
        }
    }

}

2.application.yml
添加文件保存的绝对路径:

# 文件上传路径
localPath: "D:/file/"

3.WebMvcConfig.class
添加文件路径配置,可以访问到文件:

/**
 * Created on 2023/2/27.
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Value("${localPath}")
    private String localPath;
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry handlerRegistry) {
        handlerRegistry.addResourceHandler("/static/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
        handlerRegistry.addResourceHandler("/files/**").addResourceLocations("file:"+localPath+"files\\");

        super.addResourceHandlers(handlerRegistry);

       handlerRegistry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);

        super.addResourceHandlers(handlerRegistry);
    }
}
好的,我可以帮你回答这个问题。首先需要获取到android11以上的存储权限,然后使用Storage Access Framework(SAF)来遍历文件。接着,我们可以使用DocumentFile API来过滤出指定类型的文件,最后使用lod.d来打印文件内容。 以下是一个示例代码: ```java // 获取存储权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); return; } // 打开SAF文件选择器 Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); startActivityForResult(intent, 2); // 在onActivityResult中处理文件选择结果 @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 2 && resultCode == RESULT_OK) { Uri treeUri = data.getData(); DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri); // 遍历文件并打印 for (DocumentFile file : pickedDir.listFiles()) { String fileName = file.getName(); if (fileName.endsWith(".txt") || fileName.endsWith(".doc") || fileName.endsWith(".docx") || fileName.endsWith(".pdf") || fileName.endsWith(".ppt") || fileName.endsWith(".pptx") || fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) { try { InputStream inputStream = getContentResolver().openInputStream(file.getUri()); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } Log.d("FileContents", stringBuilder.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } } ``` 请注意,上述代码仅供参考,并且可能需要根据您的实际需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王八八。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值