jsp 下载文件 AJAX不支持返回流类型 采用jquery easyui的表单提交

本文介绍了一个文件下载功能的具体实现过程,包括前端JavaScript调用、后端Java处理逻辑及文件流的传输方式。通过示例代码展示了如何从服务器获取指定ID的文件并下载到客户端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//JS

filedownLoad:function(id){

downForm = $("#fileForm").form();
downForm.form('submit', {
url : ctx+'/file/downLoad.shtml?fileid='+id,
type : 'POST',
success : function(data) {
if(!data.flag){
layer.msg("资源不存在!");
}
}
})

}



//JSP页面

 <div class="file-name">
                                        ${item.file_name} 
                                        <br>
                                        <form id="fileForm" method="post">
                <input type="hidden" id="fileid" name="file_id" value="${item.file_id}"/>
                </form>  
                                        <small>上传时间:<fmt:formatDate value="${item.upload_time}" pattern="yyyy-MM-dd"/><a href="javascript:void(0)"  onclick="fileview.filedownLoad(${item.file_id});"  style="margin-left: 40px;font-size:14px; color: #676a6c;" ><i class="glyphicon glyphicon-cloud-download"></i> </a></small>
                                    </div>

//控制层

@RequestMapping(value = "/downLoad")
public void downLoad( HttpServletResponse response,Integer fileid,PrintWriter writer) throws Exception {
JSONObject result = new JSONObject();
Map<String, Object> map = new HashMap<String, Object>();
map.put("file_id", fileid);
List<SpFile> filelist = spFileService.selectSpfileByObjectid(map);
String hostpath = SysConfigManager.getInstance().getText("/config/system/file");
String path = hostpath+filelist.get(0).getPath();
        File f = new File(path);
        if (!f.exists()) {
        result.put("flag", false);
        response.setContentType("text/html;charset=utf-8");
    writer.println(result);
        }else{
        FileUtils.down(response, path,f.getName());
        }
    }



//下载文件的方法


public static void down(HttpServletResponse response, String path,
String filename) throws Exception {
File downloadFile = new File(path);
InputStream in = null;
OutputStream out = null;
try {
response.reset(); 
response.setHeader("Content-disposition", "attachment;filename="
+ URLEncoder.encode(filename, "utf-8"));
in = new FileInputStream(downloadFile);
out = response.getOutputStream();
byte[] bytes = new byte[1024];
int length;
while ((length = in.read(bytes, 0, bytes.length)) > -1) {
out.write(bytes, 0, length);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
in.close();
out.flush();
out.close();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值