Skip to content
정명주(myeongju.jung) edited this page Jul 23, 2018 · 1 revision
package io.redutan.project.ui;

import com.dooray.wiki.api.application.file.model.AttachFileDownload;
import org.springframework.core.io.InputStreamSource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.Serializable;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * @author myeongju.jung
 */
public final class WebMvcUtils {
    private WebMvcUtils() {
        throw new UnsupportedOperationException();
    }

    public static URI locationUri(Serializable id) {
        return ServletUriComponentsBuilder.fromCurrentRequest()
                                          .path("/{id}")
                                          .buildAndExpand(id)
                                          .toUri();
    }

    public static ResponseEntity<InputStreamSource> download(AttachFileDownload download) {
        if (download.isEmpty()) {
            return ResponseEntity.notFound()
                                 .build();
        }
        return ResponseEntity.ok()
                             .headers(downloadHeaders(download))
                             .body(download.getSource());
    }

    private static HttpHeaders downloadHeaders(AttachFileDownload download) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(ContentDisposition.builder("attachment")
                                                        .filename(download.getName(), Charset.forName("UTF-8"))
                                                        .build());
        headers.setContentType(MediaType.valueOf(download.getMimeType()));
        headers.setContentLength(download.getSize());
        return headers;
    }
}
Clone this wiki locally