如何获得请求体的一部分作为输入流(请求体映射到多个字段,其中一个是输入流字段)



让我们考虑以下场景:

我需要上传非常大的文件,除此之外,我需要名称,版本和作者。我已经创建了以下端点:

@PostMapping(path = "/upload", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> upload(@RequestBody MyClass myClass) {
//do the upload using the content received as InputStream and return success
}

MyClass.java:

public class MyClass {
private String name;
private String version;
private String author;
private InputStream fileContent;
// constructor, getters and setters
}

请求正文示例:

{
"name": "article",
"version": "1",
"author": "John Smith"
"fileContent": "ZmlsZUNvbnRlbnQg" //base64 encoded tgz/zip
}

所以整个情况是保存名称,版本和作者,例如在数据库中,然后使用fileContent InputStream将其流到某个地方(因为它太大而不能将其作为bytearray)。这样的事情在春天可能发生吗?感谢所有的帮助!

我有这个功能,用于上传视频到我的intellij工作区的目录。

@RequestMapping(method = RequestMethod.POST, path = "/projects/save/video")
public String uploadVideo(@RequestParam("file") MultipartFile file, @ModelAttribute Project project) throws InterruptedException {
// check if file is empty
if (file.isEmpty()) {
System.out.println("No file");
return "redirect:/user/projects";
}
// normalize the file path
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
// save the file on the local file system
try(InputStream inputStream = file.getInputStream()) {
Path path = Paths.get(VID_UPLOAD_DIR + fileName);
Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
File directory = new File(CLASS_DIR);
if (! directory.exists()) {
directory.mkdir();
}
Path classPath = Paths.get(CLASS_DIR + fileName);
Files.copy(path, classPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
e.printStackTrace();
}
String part="../videos/"+fileName;
System.out.println(file.getSize() + " <---[]---> " + part);
member.setVideo(part);
MemberDB.projects.get(0).setTitle(project.getTitle());
MemberDB.projects.get(0).setDescription(project.getDescription());
MemberDB.projects.get(0).setLanguage(project.getLanguage());
MemberDB.projects.get(0).setTechnology(project.getTechnology());
MemberDB.projects.get(0).setVideoName(project.getVideoName());
return "redirect:/user/projects";
}

模板(使用thyymleaf)看起来像这样

<form action="#" th:action="@{/projects/save/video}" name="subform" method="post" id="addProject" th:object="${project}" enctype="multipart/form-data">
<h2 class="exempt" style="border:none;">Add project</h2>
<input class="exempt" th:field="*{title}" type="text">
<textarea class="exempt" th:field="*{description}" rows="4"></textarea>

<input class="exempt" type="hidden" th:field="*{videoName}" id="setVidName">
<input class="exempt" type="file" id="vidName" accept="video/mp4" name="file" onchange="setNameVar(this);">
<button class="exempt" type="button" onclick="submitForm();">Save project</button>
</form>

在你的应用程序属性

  • spring.servlet.multipart.max-file-size = 200 mb
  • <
  • spring.servlet.multipart.max-request-size = 200 mb/gh>
  • spring.servlet.multipart.enabled = true

相关内容

  • 没有找到相关文章

最新更新