package com.mzl.flower.web.upload;
|
|
import com.mzl.flower.base.BaseController;
|
import com.mzl.flower.config.exception.ValidationException;
|
import com.mzl.flower.dto.response.upload.UploadResultDTO;
|
import io.swagger.annotations.Api;
|
import io.swagger.annotations.ApiOperation;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.ResponseBody;
|
import org.springframework.web.bind.annotation.RestController;
|
|
import javax.servlet.http.HttpServletResponse;
|
import java.io.*;
|
import java.net.URL;
|
import java.net.URLConnection;
|
import java.net.URLEncoder;
|
|
@RestController
|
@RequestMapping("/api/download")
|
@Api(value = "文件下载", tags = "文件下载")
|
@Slf4j
|
public class FileDownloadResource extends BaseController {
|
|
@GetMapping("/file")
|
@ResponseBody
|
@ApiOperation(value = "文件下载", httpMethod = "GET", response = UploadResultDTO.class, notes = "文件下载")
|
public void downloadFile(final String fileName, final String filePath, HttpServletResponse response) throws IOException {
|
URL url = new URL(filePath);
|
URLConnection uc = url.openConnection();
|
String contentType = uc.getContentType();
|
int contentLength = uc.getContentLength();
|
if (contentType.startsWith("text/") || contentLength == -1) {
|
throw new ValidationException("文件为空");
|
}
|
try (InputStream raw = uc.getInputStream()) {
|
InputStream in = new BufferedInputStream(raw);
|
byte[] data = new byte[contentLength];
|
int offset = 0;
|
while (offset < contentLength) {
|
int bytesRead = in.read(data, offset, data.length - offset);
|
if (bytesRead == -1) {
|
break;
|
}
|
offset += bytesRead;
|
}
|
if (offset != contentLength) {
|
throw new ValidationException("文件为空");
|
}
|
// 清空response
|
response.reset();
|
// 设置response的Header
|
/*String name = fileName;
|
if(name != null){
|
name = new String(name.getBytes("gb2312"), "ISO8859-1");
|
}*/
|
response.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
|
response.addHeader("Content-Length", "" + contentLength);
|
response.setContentType("application/octet-stream");
|
try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
|
out.write(data);
|
out.flush();
|
}
|
}
|
}
|
}
|