如何在Spring Boot中创建已上传文件的列表?

huangapple go评论74阅读模式
英文:

How to create a list of uploaded files in Spring Boot?

问题

以下是您提供的内容的翻译部分:

控制器部分:

@Controller
class MyFileUploadController {

    @RequestMapping(value = "/uploadOneFile", method = RequestMethod.GET)
    public String uploadOneFileHandler(Model model) {
        MyUploadForm myUploadForm = new MyUploadForm();
        model.addAttribute("myUploadForm", myUploadForm);
        return "uploadOneFile";
    }

    @RequestMapping(value = "/uploadOneFile", method = RequestMethod.POST)
    public String uploadOneFileHandlerPOST(HttpServletRequest request, //
                                           Model model, //
                                           @ModelAttribute("myUploadForm") MyUploadForm myUploadForm) {
        return this.doUpload(request, model, myUploadForm);
    }

    // ... (其他方法类似)

    private String doUpload(HttpServletRequest request, Model model, //
                            MyUploadForm myUploadForm) {
        // ... (上传文件的逻辑)
        return "uploadResult";
    }
}

MyUploadForm类:

public class MyUploadForm {

    private String description;
    private MultipartFile[] fileDatas;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public MultipartFile[] getFileDatas() {
        return fileDatas;
    }

    public void setFileDatas(MultipartFile[] fileDatas) {
        this.fileDatas = fileDatas;
    }
}

uploadOneFile.html页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:c="http://java.sun.com/xml/ns/javaee">

<head>
    <meta charset="UTF-8">
    <title>Upload One File</title>
</head>

<body>
<th:block th:include="/_menu"></th:block>

<h3>Upload single file:</h3>

<form th:object="${myUploadForm}" method="POST"
      action="" enctype="multipart/form-data">
    Beschreibung:
    <br>
    <input th:field="*{description}" style="width:300px;"/><br/><br/>
    File to upload: <input th:field="*{fileDatas}" type="file"/><br/>
    <input type="submit" value="Upload">
</form>
</body>
</html>

这些部分是您提供的代码和HTML页面的翻译。如果您有任何其他问题或需要进一步帮助,请随时告诉我。

英文:

I want to create a list of uploaded files that are stored in a directory on my hard drive.

My Controller:

@Controller 
class MyFileUploadController {


    @RequestMapping(value = &quot;/uploadOneFile&quot;, method = RequestMethod.GET)
    public String uploadOneFileHandler(Model model) {

        MyUploadForm myUploadForm = new MyUploadForm();
        model.addAttribute(&quot;myUploadForm&quot;, myUploadForm);

        return &quot;uploadOneFile&quot;;
    }


    @RequestMapping(value = &quot;/uploadOneFile&quot;, method = RequestMethod.POST)
    public String uploadOneFileHandlerPOST(HttpServletRequest request, //
                                           Model model, //
                                           @ModelAttribute(&quot;myUploadForm&quot;) MyUploadForm myUploadForm) {

        return this.doUpload(request, model, myUploadForm);

    }


    @RequestMapping(value = &quot;/uploadMultiFile&quot;, method = RequestMethod.GET)
    public String uploadMultiFileHandler(Model model) {

        MyUploadForm myUploadForm = new MyUploadForm();
        model.addAttribute(&quot;myUploadForm&quot;, myUploadForm);

        return &quot;uploadMultiFile&quot;;
    }


    @RequestMapping(value = &quot;/uploadMultiFile&quot;, method = RequestMethod.POST)
    public String uploadMultiFileHandlerPOST(HttpServletRequest request, //
                                             Model model, //
                                             @ModelAttribute(&quot;myUploadForm&quot;) MyUploadForm myUploadForm) {

        return this.doUpload(request, model, myUploadForm);

    }

    private String doUpload(HttpServletRequest request, Model model, //
                            MyUploadForm myUploadForm) {

        String description = myUploadForm.getDescription();
        System.out.println(&quot;Description: &quot; + description);


        String uploadRootPath = request.getServletContext().getRealPath(&quot;upload&quot;);
        System.out.println(&quot;uploadRootPath=&quot; + uploadRootPath);

        File uploadRootDir = new File(&quot;(directory)&quot;);

        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }
        MultipartFile[] fileDatas = myUploadForm.getFileDatas();

        List&lt;File&gt; uploadedFiles = new ArrayList&lt;File&gt;();
        List&lt;String&gt; failedFiles = new ArrayList&lt;String&gt;();

        for (MultipartFile fileData : fileDatas) {


            String name = fileData.getOriginalFilename();
            System.out.println(&quot;Client File Name = &quot; + name);

            if (name != null &amp;&amp; name.length() &gt; 0) {
                try {

                    File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);

                    BufferedOutputStream stream = new BufferedOutputStream(new 
                    FileOutputStream(serverFile));
                    stream.write(fileData.getBytes());
                    stream.close();

                    uploadedFiles.add(serverFile);
                    System.out.println(&quot;Write file: &quot; + serverFile);
                } catch (Exception e) {
                    System.out.println(&quot;Error Write file: &quot; + name);
                    failedFiles.add(name);
                }
            }
        }
        model.addAttribute(&quot;description&quot;, description);
        model.addAttribute(&quot;uploadedFiles&quot;, uploadedFiles);
        model.addAttribute(&quot;failedFiles&quot;, failedFiles);
        return &quot;uploadResult&quot;;
    }
}

MyUploadForm

public class MyUploadForm {

    private String description;


    private MultipartFile[] fileDatas;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public MultipartFile[] getFileDatas() {
        return fileDatas;
    }

    public void setFileDatas(MultipartFile[] fileDatas) {
        this.fileDatas = fileDatas;
    }

}

The User can upload his files on the uploadOneFile.html.

uploadOneFile.html

&lt;!DOCTYPE html&gt;
&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot; xmlns:c=&quot;http://java.sun.com/xml/ns/javaee&quot;&gt;

&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;title&gt;Upload One File&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;th:block th:include=&quot;/_menu&quot;&gt;&lt;/th:block&gt;

&lt;h3&gt;Upload single file:&lt;/h3&gt;

&lt;form th:object=&quot;${myUploadForm}&quot; method=&quot;POST&quot;
      action=&quot;&quot; enctype=&quot;multipart/form-data&quot;&gt;
    Beschreibung:
    &lt;br&gt;
    &lt;input th:field=&quot;*{description}&quot; style=&quot;width:300px;&quot;/&gt;
    &lt;br/&gt;&lt;br/&gt;
    File to upload: &lt;input th:field=&quot;*{fileDatas}&quot; type=&quot;file&quot;/&gt;
    &lt;br/&gt;
    &lt;input type=&quot;submit&quot; value=&quot;Upload&quot;&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

The uploaded files should then be displayed on the index page. Aswell it should be possible to download the files with just clicking on them.

I'm a beginner in Spring Boot so can you help me? If you need more informations let it me know.

答案1

得分: 1

你可以在那个页面上创建一个表格(HTML布局可以根据设计等选择)。

主要逻辑可能是:

  • 从目录中获取文件列表。
  • 将文件名存储在SET、LIST或您选择的其他数据结构中。
  • 通过一些模型将先前的列表传递到UI,通过索引页面控制器。
  • 渲染文件列表。
  • 在单击特定文件时,调用端点通过名称下载文件。

一些初始感兴趣的代码可能如下所示:

File directoryPath = new File("D:\\PATH\\OF\\DIRECTORY");
FileFilter textFilefilter = new FileFilter(){
    public boolean accept(File file) {
    boolean isFile = file.isFile();
        if (isFile) {
           return true;
        } else {
           return false;
        }
    }
};
//所有文件的列表(仅限文件)
File filesList[] = directoryPath.listFiles(textFilefilter);
System.out.println("指定目录中的文件列表:");
for(File file : filesList) {
    System.out.println("文件名:" + file.getName());
    System.out.println("文件路径:" + file.getAbsolutePath());
    System.out.println("大小:" + file.getTotalSpace());
    System.out.println(" ");
}
英文:

You can create a table on that page (html layout you can choose as per design etc..)

Main logic can be:-

  • Get list of file's from the directory.
  • Have the names of files stored in a SET or LIST or something of your choice.
  • Pass the previous list onto UI using some model via the index page controller.
  • Render the list of files.
  • Upon clicking the particular file, call the endpoint to download file by name.

Some Code of initial interest could be like below:-


File directoryPath = new File(&quot;D:\\PATH\\OF\\DIRECTORY&quot;);
FileFilter textFilefilter = new FileFilter(){
    public boolean accept(File file) {
    boolean isFile = file.isFile();
        if (isFile) {
           return true;
        } else {
           return false;
        }
    }
};
//List of all the files (only files)
File filesList[] = directoryPath.listFiles(textFilefilter);
System.out.println(&quot;List of the files in the specified directory:&quot;);
for(File file : filesList) {
    System.out.println(&quot;File-name: &quot;+file.getName());
    System.out.println(&quot;File-path: &quot;+file.getAbsolutePath());
    System.out.println(&quot;Size: &quot;+file.getTotalSpace());
    System.out.println(&quot; &quot;);
}
 

</details>



huangapple
  • 本文由 发表于 2020年10月4日 23:17:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64196381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定