Reputation: 57
I'm trying to implement a file upload function using "vaadin-upload". I have a locally built file upload server implemented with Spring boot, and I want to use its API to upload files. I want to use this API to upload files input from "vaadin-upload".
The API specification is this.
The API reference for "vaadin-upload" does not tell me how to execute the API. I don't know how to run the API. Please tell me.
index.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>
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;
}
}
FileController.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());
}
}
Upvotes: 1
Views: 743
Reputation: 815
You can configure the upload request by setting the respective attributes on the Upload component, for example:
<vaadin-upload
target="http://localhost:8080/uploadFile"
headers='{"Content-Type": "multipart/form-data"}'
form-data-name="file"
></vaadin-upload>
Not 100% sure about form-data-name
, but looking at the component's sources it should do what you want.
Upload already contains a button, so you don't need to add your own button to trigger the upload. If you still want to trigger the upload programmatically for some reason, you can use Upload.uploadFiles.
Reference: Upload documentation, Upload API docs
Upvotes: 1