圖片下載 (hqm精簡版)

四六之間發表於2020-11-06

FileDownloadController.java

import cn.hutool.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("applet/")
@Api(tags = "圖片下載")
public class FileDownloadController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileDownloadController.class);

	/**
	 * 圖片下載
	 */
	@GetMapping(value = "/download")
	@ApiOperation("圖片下載")
	public void download(@RequestParam("filePath") String filePath, HttpServletResponse response) {
		try {
			if (StringUtils.isEmpty(filePath)){
				return;
			}
			String host = getTopUrl();
			String fileName = UUID.randomUUID() + ".jpg";
			response.setHeader("content-type", "application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment;filename="+fileName);

			ServletOutputStream out = response.getOutputStream();
			if (!filePath.startsWith("http")){
				filePath = host + "/" + filePath;
			}
			HttpUtil.download(filePath, out, true);
		} catch (Exception e) {
			LOGGER.error("下載檔案失敗", e);
		}
	}

}

相關文章