Vue前端代码
function downloadFile(fileId, fileName) {
window.open("/downloadFile?fileId=?&fileName=" + encodeURI(fileName));
}
后台代码
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@RequestMapping("/downloadFile")
private void downLoadFile(HttpServletRequest request, HttpServletResponse response, String fileId) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload");
try {
MyFile myFile = service.queryFileInfoById(fileId);
String fileName = URLEncoder.encode(myFile.getFileName(),"UTF-8");//转Unicode不然ie会乱码
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
//获取文件路径
String fileUrl = myFile.getFileUrl();
//获取项目在服务器上的真实路径
//String realPath = request.getSession().getServletContext().getRealPath("/");
//如果数据库中存的路径是文件在项目下的那个目录的话,就需要和上面的路径进行拼接(‘File.separator’是区分服务器的路径分隔符)
//fileUrl = realPath + File.separator + fileUrl + File.separator + fileName;
//如果数据库中存的路径是文件在服务器上的真实路径的话,可以直接使用
File file = new File(fileUrl);
if (!file.exists()) {
response.sendError(404, "File not found!");
return;
}
long fileLength = file.length();
response.setHeader("Content-Length", String.valueOf(fileLength));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}