JAVA实现从Linux服务器上下载文件

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();
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值