前端显示:
前端代码:
<a href="/api/download">Download</a>
后台使用的框架是springboot,代码如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@RestController
public class FileDownloadController {
@RequestMapping(value = "/api/download")
public String apply(HttpServletRequest request, HttpServletResponse response) {
//被下载的文件在服务器中的路径,
String downloadFilePath = "download/view.jpg";
//被下载文件的名称,下载之后的文件显示的名字,
可以用现在的view.jpg,也可以使用其它,比如:a.jpg
String fileName = "Chrysanthemum.jpg";
File file = new File(downloadFilePath);
if (file.exists()) {
// 设置强制下载不打开
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream outputStream = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = bis.read(buffer);
}
return "success";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return "file doesn't found!";
}
}
下载效果如下: