Created
November 28, 2020 09:51
-
-
Save AmaranthLIS/4eb5f3d64db2564422e38af944d0ce81 to your computer and use it in GitHub Desktop.
micronaut file upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example.micronaut; | |
//tag::imports[] | |
import io.micronaut.http.HttpResponse; | |
import io.micronaut.http.MediaType; | |
import io.micronaut.http.annotation.Consumes; | |
import io.micronaut.http.annotation.Controller; | |
import io.micronaut.http.annotation.Get; | |
import io.micronaut.http.annotation.Post; | |
import io.micronaut.http.multipart.CompletedFileUpload; | |
import io.micronaut.views.View; | |
import javax.annotation.Nullable; | |
import java.net.URI; | |
import java.util.HashMap; | |
import java.util.Map; | |
//end::imports[] | |
@Controller("/") | |
public class HomeController { | |
public static final String REDIRECT_PATH = "/"; | |
public static String IMAGE_KEY = "some-file.png"; | |
private final FileRepository fileRepository; | |
public HomeController(FileRepository fileRepository) { //inject | |
this.fileRepository = fileRepository; | |
} | |
@View("home") | |
@Get | |
public Map<String, Object> index() { | |
return Map.of("message", "Hi there! This is simple example of upload file"); | |
} | |
@Consumes(MediaType.MULTIPART_FORM_DATA) | |
@Post("/upload") | |
public HttpResponse upload(CompletedFileUpload file) { | |
if ((file.getFilename() == null || file.getFilename().equals(""))) { | |
return HttpResponse.seeOther(URI.create(REDIRECT_PATH)); | |
} | |
fileRepository.upload(IMAGE_KEY, file); | |
return HttpResponse.seeOther(URI.create(REDIRECT_PATH)); | |
} | |
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) | |
@Post("/delete") | |
public HttpResponse delete(String key) { | |
fileRepository.delete(key); | |
return HttpResponse.seeOther(URI.create(REDIRECT_PATH)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment