在春季上传多个文件,每个文件都包含其他信息

时间:2019-03-20 10:44:18

标签: javascript spring multiple-file-upload

我是spring boot和js的新手,我正在尝试上传多个文件,每个文件都具有描述等其他信息。

对象:

public class BookDto {
    private String title;
    private String author;
    private List<PageDto> pageDtoList;
    // getters setters
}

public class PageDto {
    private String description;
    private MultipartFile file;
    // getters setters
}

控制器:

public class UploadController{

    @PostMapping("/upload")
    public ResponseEntity createGenre(@RequestBody BookDto bookDto){
       // do something with data
    }
}

HTML:

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" multiple onclick="postRequest(event)">
    <input type="submit" value="Upload" name="submit">
</form>

JS:

function postRequest(event){
    event.preventDefault();
    var files = [].slice.call(event.target.files);
    var pageList = [];
    for (var i=0; i<files.length; i++) { 
        pageList.push(new Page( i + "some description",files[i]));
    }
    var newBook = new Book();
    newbook.pageList = pageList;
    book.author = "author1";
    book.title = "title1";
    $.ajax({
        type: "POST",
        data: // i don't really know what to put here,
        url: "/upload",
        success: function (response) {
            // success
        },
        error: function (result) {
            // error
        }
    });

}

function Book(title, author, chapter, pageList){
    this.title = title;
    this.author = author;
    this.pageList = pageList;
}

function Page(description, file) {
    this.description = description;
    this.file = file;
}

我想知道是否可以按照对象描述上传文件,还是必须分别上传文件。

1 个答案:

答案 0 :(得分:0)

为了根据请求创建书本实例,请考虑到您具有以下路线:

@PostMapping("/createBook")
    public ResponseEntity createBook(@RequestBody BookDto bookDto){
       // do something with data
    }

您可以从客户端继续进行以下操作:


const book = {
   author: "George Orwell",
   title: "1984",
   pageDtoList: []
};

$.ajax({
        type: "POST",
        data: book,
        url: "/createBook",
        success: function (response) {
            // success
        },
        error: function (result) {
            // error
        }
    });

然后,您可以添加具有相同逻辑但页面设置为临时为null的页面,并在给定页面ID后上传文件。

@PostMapping("/addPageToBook")
    public ResponseEntity addPage(@RequestParam("bookid") String bookId, 
                                  @RequestBody PageDto pageDto){

       // add a page instance to your book
    }

然后您可以设置页面内容:

@PostMapping("/setPageContent")
    public ResponseEntity setPage(@RequestParam("bookid") String bookId, 
                                  @RequestParam("pageid") String pageId,
                                  @RequestParam("file") MultipartFile content){

       // set content to page, ensure book dto is updated with last page instance
    }

您需要使用https://developer.mozilla.org/en-US/docs/Web/API/FormData进行AJAX上载,但是(取决于您的使用情况)一个简单的文件输入按钮+提交就足够了。