java - 在Ubuntu文件系统中上传文件后,文件没有格式

标签 java

我在文件系统中上传文件时遇到一些问题,上传文件后没有格式。例如,如果我上传 .doc 格式的文件,上传后它的名字中没有任何结尾。

这是上传文件的方法

@RequestMapping(value = "/uploadingPageFileForDeputeAppeal", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("name") String name,
                             @RequestParam(value = "id", required = true) int id,
                             Model model){
        LOGGER.debug("Receive request to add file");
        if(!file.isEmpty()){
            try {
                byte [] bytes = file.getBytes();

                //Creating the directory to store file
                String path = System.getProperty("user.home");
                File directory = new File(path + File.separator + "DeputeAppealsFiles");
                if(!directory.exists())
                    directory.mkdirs();

                // Create the file on server
                File serverFile = new File(directory.getAbsolutePath() + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
                DeputeAppeal deputeAppeal = deputeAppealService.getById(id);
                deputeAppealService.editFilePath(deputeAppeal, serverFile.getAbsolutePath());
                model.addAttribute("deputeAppealId", deputeAppeal);

            } catch (Exception e) {
                return "You failed to upload " + file.getName() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + file.getName()
                    + " because the file was empty.";
        }

        return "deputeAppealView/addedFile";
    }

有什么想法吗?这很麻烦,因为上传文件后我需要获取带有标签的文件,并且我认为我无法获取它,因为文件路径保存时没有格式,并且我无法在文件系统中获取它

最佳答案

您使用 @RequestParam("name") String name 中的名称保存文件,因此您应该知道在那里传递的内容。

如果您不想传递带扩展名的名称,可以从 MultipartFile 获取它。你可以这样做:

file.getOriginalFilename().split("\\.")[1]; // it will fail, if there is no extension, so you should add error handling

或根据内容类型查找:

file.getContentType();

关于java - 在Ubuntu文件系统中上传文件后,文件没有格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466341/

相关文章:

amazon-ec2 - 让 AWS ElasticBeanstalk 与 Sun JDK 配合使用时遇到问题

java - BufferedReader 从套接字读取

java - JLabel getToolTipText() 不返回已设置的工具提示

java - 安卓 :Activity is blocking with black screen when it occur Exception

java - 如何在 64 位机器上运行为 32 位制作的 API?

java - 使用 Ebean NullPointerException 玩 2.4

java - 使用 Spring @RequestParam 无法在 Controller 中获取 '#' 符号

java - jOOQ - 从 psql 查询构建更新

java - @Valid 在 Spring java 中不起作用

java - GWT Eclipse java插件: Code assist does't work in event handlers