vaadin - 我想使用 vaadin-upload 调用文件上传 API
问题描述
我正在尝试使用“vaadin-upload”实现文件上传功能。我有一个使用 Spring boot 实现的本地构建的文件上传服务器,我想使用它的 API 来上传文件。我想使用这个 API 上传从“vaadin-upload”输入的文件。
API规范是这样的。
- [网址] http://localhost:8080/uploadFile
- [标题] 内容类型:multipart/form-data
- [requestparam] 文件:多部分文件
“ vaadin-upload ”的 API 参考并没有告诉我如何执行 API。我不知道如何运行 API。请告诉我。
索引.html
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8"/>
<title>sample</title>
<script type="module" src="./out/api-sample/file-upload.js"></script>
<file-upload></file-upload>
文件上传.ts
import {customElement} from 'lit/decorators.js';
import {html, LitElement} from 'lit';
import '@vaadin/vaadin-upload';
@customElement('file-upload')
export class FileUpload extends LitElement {
render() {
return html`
<vaadin-upload></vaadin-upload>
<vaadin-button @click="${this.upload}">upload</vaadin-button>
`;
}
upload() {
// ???
}
}
declare global {
interface HTMLElementTagNameMap {
'file-upload': FileUpload;
}
}
文件控制器.java
package com.example.demo.controller;
import com.example.demo.date.UploadFileResponse;
import com.example.demo.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
public class FileController {
private final FileStorageService fileStorageService;
@Autowired
public FileController(FileStorageService fileStorageService) {
this.fileStorageService = fileStorageService;
}
@PostMapping("/uploadFile")
public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/downloadFile/")
.path(fileName)
.toUriString();
return new UploadFileResponse(fileName, fileDownloadUri, file.getContentType(), file.getSize());
}
}
解决方案
您可以通过在 Upload 组件上设置相应的属性来配置上传请求,例如:
<vaadin-upload
target="http://localhost:8080/uploadFile"
headers='{"Content-Type": "multipart/form-data"}'
form-data-name="file"
></vaadin-upload>
不是 100% 确定form-data-name
,但是查看组件的源代码应该可以满足您的需求。
上传已经包含一个按钮,所以你不需要添加自己的按钮来触发上传。如果您出于某种原因仍想以编程方式触发上传,则可以使用Upload.uploadFiles。
推荐阅读
- c++ - 如何为 Unreal Engine 4 启用 /arch:AVX?
- python - Windows 10 上的 Python Matplotlib 安装问题
- python - 在 Pandas 中迭代地分配唯一 ID
- javascript - 任何设计模式都可以替换 javascript 中的 promise/then 链?
- xml - 在 xslt 中映射 xml 元素的最佳方法
- r - R - 为 lapply 定义几个阶跃函数
- python - 我们如何能够直接从 openpyxl 包中调用 load_workbook
- sql - 使用 SQL 列表中的变量运行 for 循环
- javascript - Laravel Fav/Unfav 功能,实现 ajax
- html - 当它们之间没有空格时,为什么不回绕到下一行