import org
.springframework
.http
.HttpHeaders
;
import org
.springframework
.web
.bind
.annotation
.*
;
import javax
.servlet
.ServletOutputStream
;
import javax
.servlet
.http
.HttpServletResponse
;
import java
.io
.*
;
import java
.net
.URLEncoder
;
import java
.util
.List
;
@RestController
public class DownloadController {
public static void main(String
[] args
) {
}
@RequestMapping(value
= "download", method
= RequestMethod
.GET
)
public void download(HttpServletResponse response
) throws IOException
{
FileInputStream in
= null
;
BufferedInputStream bfIn
= null
;
ServletOutputStream outputStream
= null
;
File file
= null
;
try {
String filePath
= System
.getProperty("user.dir") + "\\" + "155.pdf";
System
.out
.println("filePath = [" + filePath
+ "]");
file
= new File(filePath
);
in
= new FileInputStream(file
);
bfIn
= new BufferedInputStream(in
);
response
.setContentType("application/pdf");
response
.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder
.encode(filePath
.substring(0, filePath
.lastIndexOf(".")), "utf-8") + filePath
.substring(filePath
.lastIndexOf(".")));
outputStream
= response
.getOutputStream();
byte[] buff
= new byte[1024];
int len
;
while ((len
= bfIn
.read(buff
)) != -1) {
outputStream
.write(buff
, 0 , buff
.length
);
}
} catch (Exception e
) {
throw e
;
} finally {
if (outputStream
!= null
) {
outputStream
.close();
}
if (bfIn
!= null
) {
bfIn
.close();
}
if (in
!= null
) {
in
.close();
}
}
}
@RequestMapping(value
= "download2", method
= RequestMethod
.POST
)
public void download(HttpServletResponse response
, @RequestHeader HttpHeaders headers
) throws IOException
{
FileInputStream in
= null
;
BufferedInputStream bfIn
= null
;
ServletOutputStream outputStream
= null
;
File file
= null
;
try {
System
.out
.println("headers = [" + headers
.size() + "]");
List
<String> fileNameList
= headers
.get("fileName");
String fileName
= fileNameList
.get(0);
System
.out
.println("fileName = [" + fileName
+ "]");
String filePath
= System
.getProperty("user.dir") + "\\" + fileName
;
System
.out
.println("filePath = [" + filePath
+ "]");
file
= new File(filePath
);
in
= new FileInputStream(file
);
bfIn
= new BufferedInputStream(in
);
response
.setContentType("application/pdf");
response
.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder
.encode(fileName
.substring(0, fileName
.indexOf(".")), "utf-8") + filePath
.substring(filePath
.lastIndexOf(".")));
outputStream
= response
.getOutputStream();
byte[] buff
= new byte[1024];
int len
;
while ((len
= bfIn
.read(buff
)) != -1) {
outputStream
.write(buff
, 0 , buff
.length
);
}
} catch (Exception e
) {
throw e
;
} finally {
if (outputStream
!= null
) {
outputStream
.close();
}
if (bfIn
!= null
) {
bfIn
.close();
}
if (in
!= null
) {
in
.close();
}
}
}
}
download1 请求示例:
download2 请求示例: