`
huangyongxing310
  • 浏览: 499455 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

spring MVC 下载文件

 
阅读更多
@RequestMapping (value="/downloadSalesReport")
    @ResponseBody
    public void downloadSalesReport( String id,HttpServletResponse response) throws  Exception {
    	BufferedInputStream in = null;  
        BufferedOutputStream out = null;  
        try {  
      
        	String fileName = "D:\\salesReportTest\\12345.xlsx";
        	String fileOutName = "测试salesReport.xlsx";
        	
        	fileOutName = new String(fileOutName.getBytes("UTF-8"), "ISO8859-1");
//        	action.setFilename(new String(fileName.getBytes("gbk"),"iso8859-1"));
        	
            File file = new File(fileName);  
            in = new BufferedInputStream(new FileInputStream(file));  
            out = new BufferedOutputStream(response.getOutputStream());  
            response.setContentType(new MimetypesFileTypeMap().getContentType(file));// 设置response内容的类型  
            response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息  
            byte[] buffer = new byte[2048];  
            int length = 0;  
            while ((length = in.read(buffer)) > 0) {  
                out.write(buffer, 0, length);  
            }  
            out.flush();  
        } catch (IOException e) {  
        	 e.printStackTrace();
        } finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
                if (out != null) {  
                    out.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }




    @RequestMapping (value="/downloadSalesReport")
    @ResponseBody
    public void downloadSalesReport( String id,HttpServletResponse response) throws  Exception {
    	BufferedInputStream in = null;  
        BufferedOutputStream out = null;  
        try {  
      
        	String fileName = "D:\\salesReportTest\\12345.xlsx";
//        	/usr/HIP/dtomcat_MALL_pre/webapps/images/userfiles/policy
//        	02d40fb0864941798541850daef8d953.png
//        	File f = File.createTempFile(System.currentTimeMillis() + "_", ".downloadByIds");
//        	 FileOutputStream fo = new FileOutputStream(f);
        	
//        	if(id==null || id.equals("")) {
//        		throw new RuntimeException("id为空");
//        	}
//        	
//        	SalesReport salesReport = salesReportService.selectById(id);
//        	if(id==null || id.equals("")) {
//        		throw new RuntimeException(id + ":对应的数据不存在");
//        	}
//        	
//        	
//        	String fileOutName = salesReport.getFileName();
//        	if(fileOutName==null||fileOutName.equals("")) {
//        		throw new RuntimeException(id + ":对应的数据文件名为空");
//        	}
////        	String fileOutName = salesReport.getFileName();
        	
        	
        	
        	ftpService.downloadFile("/userfiles/policy/02d40fb0864941798541850daef8d953.png",response.getOutputStream());
        	

//        	String fileName = "D:\\salesReportTest\\12345.xlsx";
//        	String fileOutName = "测试salesReport.xlsx";
        	String fileOutName = "测试salesReport.png";
        	
        	fileOutName = new String(fileOutName.getBytes("UTF-8"), "ISO8859-1");
//        	action.setFilename(new String(fileName.getBytes("gbk"),"iso8859-1"));
        	
//            File file = new File(fileName);  
//            in = new BufferedInputStream(new FileInputStream(file));  
//            out = new BufferedOutputStream(response.getOutputStream());  
//            response.setContentType(new MimetypesFileTypeMap().getContentType(file));// 设置response内容的类型  
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM);// 设置response内容的类型  
            
            response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息  
//            byte[] buffer = new byte[2048];  
//            int length = 0;  
//            while ((length = in.read(buffer)) > 0) {  
//                out.write(buffer, 0, length);  
//            }  
//            out.flush();  
        } catch (IOException e) {  
        	 e.printStackTrace();
        	 response.sendError(500, e.getMessage());
        } finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
                if (out != null) {  
                    out.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }







	@RequestMapping(value = "/downloadSalesReport")
	@ResponseBody
	public void downloadSalesReport(String id, HttpServletRequest request,HttpServletResponse response) throws Exception {
//    	BufferedInputStream in = null;  
//        BufferedOutputStream out = null;  
		try {

//			if (id == null || id.equals("")) {
//				throw new RuntimeException("id为空");
//			}
//
//			SalesReport salesReport = salesReportService.selectById(id);
//			if (id == null || id.equals("")) {
//				throw new RuntimeException(id + ":对应的数据不存在");
//			}
//
//			String fileOutName = salesReport.getFileName();
//			if (fileOutName == null || fileOutName.equals("")) {
//				throw new RuntimeException(id + ":对应的数据文件名为空");
//			}
//
//			String folderName = salesReport.getFolderName();
//			if (folderName == null || folderName.equals("")) {
//				throw new RuntimeException(id + ":对应的数据文件路径为空");
//			}

			String fileOutName = "的数据文件dsd.png";
//			String fileName = folderName + "/" + fileOutName;
			String fileName = "/userfiles/policy/02d40fb0864941798541850daef8d953.png";

			ftpService.downloadFile(fileName, response.getOutputStream());
			
			//IE与chrome文件名乱码处理
			 String header = request.getHeader("User-Agent").toUpperCase();
		        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
		        	fileOutName = URLEncoder.encode(fileOutName, "utf-8");
		        	fileOutName = fileOutName.replace("+", "%20");    //IE下载文件名空格变+号问题
		        } else {
		        	fileOutName = new String(fileOutName.getBytes(), "ISO8859-1");
		        }
			
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息
  
		} catch (IOException e) {
			e.printStackTrace();
			response.sendError(500, e.getMessage());
		} 
	}







//在头部返回特殊信息

		@RequestMapping(value = "/downloadSalesReport")
	@ResponseBody
	public String   downloadSalesReport(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
//    	BufferedInputStream in = null;  
//        BufferedOutputStream out = null;  
		try {

			if (id == null || id.equals("")) {
				throw new RuntimeException("id为空");
			}

			SalesReport salesReport = salesReportService.selectById(id);
			if (id == null || id.equals("")) {
				throw new RuntimeException(id + ":对应的数据不存在");
			}
			
//			int num = salesReport.getDownloaded();
//			if (num > 0) {
//				throw new RuntimeException("已经下载过这文件");
//			}
			

			String fileOutName = salesReport.getFileName();
			if (fileOutName == null || fileOutName.equals("")) {
				throw new RuntimeException(id + ":对应的数据文件名为空");
			}

			String folderName = salesReport.getFolderName();
			if (folderName == null || folderName.equals("")) {
				throw new RuntimeException(id + ":对应的数据文件路径为空");
			}

			// -----------
			SessionUser sessionUser = UserUtils.getCurrentUser();
			if (sessionUser == null) {
				throw new RuntimeException("用户信息为空");
			}

			String loginName = sessionUser.getLoginName();

			if (loginName == null || loginName.equals("")) {
				throw new RuntimeException("用户loginName为空");
			}

			if (folderName.indexOf(loginName) < 0) {
				throw new RuntimeException(folderName + ":不是当前用户的文件路径");
			}

//			String fileOutName = "的数据文件dsd.png";
			String fileName = folderName + "/" + fileOutName;
			SysLog.log("fileName == " + fileName);
//		 fileOutName = "的数据文件dsd.xlsx";
			// IE与chrome文件名乱码处理
			String header = request.getHeader("User-Agent").toUpperCase();
			if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
				fileOutName = URLEncoder.encode(fileOutName, "utf-8");
				fileOutName = fileOutName.replace("+", "%20"); // IE下载文件名空格变+号问题
			} else {
				fileOutName = new String(fileOutName.getBytes(), "ISO8859-1");
			}

			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息

			boolean flag = ftpService.downloadFile(fileName, response.getOutputStream(), "2");
			if (!flag) {
				throw new RuntimeException("FTP获取文件失败");
			}

			// =========理更新信息
			salesReport.setDlId(loginName);
			salesReport.setDlDate(new Date());
			salesReport.setDownloaded(1);
			salesReportService.updateById(salesReport);
			return null;

		} catch (Exception e) {
			e.printStackTrace();
//			response.sendError(500, e.getMessage());
//			throw e;
//			return e.getMessage();
			response.setHeader("sut", "sutTESTTEST");// 设置头部信息
			response.setContentType("application/json;charset=UTF-8");
			response.setHeader("Content-disposition", "");// 设置头部信息
			
			
			response.getOutputStream().write(new String(e.getMessage().getBytes(), "GBK").getBytes());
			return null;

		}
		
//		return null;

	}















https://blog.csdn.net/dreaming317/article/details/82591600
https://blog.csdn.net/z69183787/article/details/80910606




https://blog.csdn.net/qq_30999361/article/details/84820420(在AJAX中发请求下载文件)


//下载不打开
@GetMapping("/getFile/{dbKey}/{id}")
	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
	@ResponseBody
	public ResponseEntity<byte[]> getFile(
			@ApiParam(name = "dbKey", value = "dbKey", required = true) @PathVariable String dbKey,
			@ApiParam(name = "id", value = "附件id", required = true) @PathVariable String id) throws Exception {
		LogUtils.info(id, "getFile");
		try {
			if (dbKey == null || dbKey.equals("") || dbKey.length() > 2) {
				ExceptionUtils.throwRuntimeException("DbKey不合规则");
			}

			if (id == null || id.equals("")) {
				ExceptionUtils.throwRuntimeException("文件id不合规则");
			}

			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
			sql = sql.replaceAll("##id##", id);

			List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapBySQL(sql);

			if (mapList == null || mapList.size() == 0) {
				return null;
			}

			String name = StringUtils.toNotNullString(mapList.get(0).get("file_name"));

			HttpHeaders headers = new HttpHeaders();
			String fileName = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
			headers.setContentDispositionFormData("fileName", fileName);
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			FileInfoService.downloadById(dbKey, id, baos);

			return new ResponseEntity(baos.toByteArray(), headers, HttpStatus.CREATED);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {

		}
	}



function downFileDeal(pk,dbKey) {

    var url = process.env.VUE_APP_BASE_API +apiUrl.getFile +"/" + dbKey+"/"+pk;

    commonConsole(url, "url");

    let a = document.createElement('a')
    a.href =url
    a.click();
}





package com.haday.springbootplus.supermarketSys.fileUpload.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.haday.springbootplus.common.vo.Paging;
import com.haday.springbootplus.manage.service.ManageServ;
import com.haday.springbootplus.manage.service.impl.LoadDataServiceImpl;
import com.haday.springbootplus.supermarketSys.attach.service.FileInfoService;
import com.haday.springbootplus.supermarketSys.fileUpload.param.DeleteFileParam;
import com.haday.springbootplus.supermarketSys.fileUpload.param.FileUploadParam;
import com.haday.springbootplus.supermarketSys.fileUpload.param.GetFileListParam;
import com.haday.springbootplus.supermarketSys.fileUpload.param.GetFilesParam;
import com.haday.springbootplus.util.BaseScanSqlCommand;
import com.haday.springbootplus.util.ExceptionUtils;
import com.haday.springbootplus.util.FileUtils;
import com.haday.springbootplus.util.ListUtils;
import com.haday.springbootplus.util.LogUtils;
import com.haday.springbootplus.util.ObjectValidityUtils;
import com.haday.springbootplus.util.ResultUtils;
import com.haday.springbootplus.util.StringUtils;
import com.haday.springbootplus.util.UUIDUtil;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api("附件管理")
@RequestMapping("/FileController")
public class FileController {

//	public static final String DBKEY = "1";

	@Autowired
	FileInfoService FileInfoService;

//
//    @Autowired
//    AttachInfoMapper attachInfoMapper;

//	@Autowired
//	FTPService ftpService;

	@Autowired
	private ManageServ manageServ;

	@Autowired
	private LoadDataServiceImpl loadDataServiceImpl;

	@Autowired
	protected HttpServletRequest request; // 这里可以获取到request
	@Autowired
	protected HttpServletResponse response;

//	@PostMapping("/fileUploadTest")
//	@ApiOperation(value = "附件上传", notes = "列表", response = String.class)
//	@ResponseBody
//	public Object fileUploadTest(@RequestParam("file") MultipartFile file) throws Exception {
//		File uploadFile = null;
//		try {
////			 产品目录
//			String busField = request.getParameter("busField");
//			String busKey = request.getParameter("busKey");
//			String busType = request.getParameter("busType");
//			String describe = request.getParameter("describe");
//			String dbKey = request.getParameter("dbKey");
//			String fileName = request.getParameter("fileName");
////			String busField = request.getParameter("busField");
//			LogUtils.info(busField, "uuid");
//
////			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
////			Iterator<String> iter = multiRequest.getFileNames();
//
//////			MultipartFile file = file;
////
//			if (file == null) {
//				ExceptionUtils.throwRuntimeException("上传文件为空");
//			}
//			if (dbKey == null) {
//				ExceptionUtils.throwRuntimeException("上传DbKey为空");
//			}
//			if (busField == null) {
//				ExceptionUtils.throwRuntimeException("上传BusField为空");
//			}
//			if (busType == null) {
//				ExceptionUtils.throwRuntimeException("上传BusType为空");
//			}
//			if (busKey == null) {
//				ExceptionUtils.throwRuntimeException("上传BusKey为空");
//			}
//			if (fileName == null) {
//				ExceptionUtils.throwRuntimeException("上传FileName为空");
//			}
////
////			// ----------------
//			LogUtils.info(file.getOriginalFilename(), "OriginalFilename");
//			fileName = fileName + "_" + UUIDUtil.getUUID() + FileUtils.getExtendName(file.getOriginalFilename());
//			LogUtils.info(fileName, "fileName");
////
////			// ----------------
////
//			uploadFile = new File(fileName); // 创建了一个File对象没有创建文件
//			FileUtil.writeFromStream(file.getInputStream(), uploadFile);
////
//			String storeName = fileName;
//			String uploadPath = StrUtil.concat(true, busField, StrUtil.SLASH, busKey);
//			LogUtils.info(uploadPath, "uploadPath");
////
//			Map<String, String> map = FileInfoService.saveAttach(dbKey, busField, busKey, busType, storeName,
//					uploadFile, uploadPath, describe);
////			// ----------------
//			if (MapUtil.getStr(map, "flag").equalsIgnoreCase("1")) {
//				Object object = ResultUtils.getSuccessResult(map);
//				LogUtils.info(object, "FileUpload return object");
//				return object;
//			} else {
//				Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(map));
////				Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(""));
////				LogUtils.info(object, "FileUpload return object");
//				return object;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			return ResultUtils.getErrorResult(e);
//		} finally {
//			if (uploadFile != null) {
//				// 会在本地产生临时文件,用完后需要删除
//				if (uploadFile.exists()) {
//					FileUtil.del(uploadFile);
//				}
//			}
//		}
//
//	}

	@PostMapping("/fileUpload")
	@ApiOperation(value = "附件上传", notes = "列表", response = String.class)
	@ResponseBody
	public Object fileUpload(@RequestParam("file") MultipartFile file, @RequestParam String busField,
			@RequestParam String busKey, @RequestParam String busType, @RequestParam String describe,
			@RequestParam String dbKey, @RequestParam String fileName) throws Exception {
		File uploadFile = null;
		try {
//			 产品目录
			String uuid = request.getParameter("busField");
			if (file == null) {
				ExceptionUtils.throwRuntimeException("上传文件为空");
			}
			if (dbKey == null) {
				ExceptionUtils.throwRuntimeException("上传DbKey为空");
			}
			if (busField == null) {
				ExceptionUtils.throwRuntimeException("上传BusField为空");
			}
			if (busType == null) {
				ExceptionUtils.throwRuntimeException("上传BusType为空");
			}
			if (busKey == null) {
				ExceptionUtils.throwRuntimeException("上传BusKey为空");
			}
			if (fileName == null) {
				ExceptionUtils.throwRuntimeException("上传FileName为空");
			}

			// ----------------
			LogUtils.info(file.getOriginalFilename(), "OriginalFilename");
			fileName = fileName + "_" + UUIDUtil.getUUID() + FileUtils.getExtendName(file.getOriginalFilename());
			LogUtils.info(fileName, "fileName");
			//
//						// ----------------
			//
			uploadFile = new File(fileName); // 创建了一个File对象没有创建文件
			FileUtil.writeFromStream(file.getInputStream(), uploadFile);
			//
			String storeName = fileName;
			String uploadPath = StrUtil.concat(true, busField, StrUtil.SLASH, busKey);
			LogUtils.info(uploadPath, "uploadPath");
			//
			Map<String, String> map = FileInfoService.saveAttach(dbKey, busField, busKey, busType, storeName,
					uploadFile, uploadPath, describe);
//						// ----------------
			if (MapUtil.getStr(map, "flag").equalsIgnoreCase("1")) {
				Object object = ResultUtils.getSuccessResult(map);
				LogUtils.info(object, "FileUpload return object");
				return object;
			} else {
				Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(map));
//							Object object = ResultUtils.getResult(false, "附件保存失败,请联系管理员!", JSON.toJSONString(""));
//							LogUtils.info(object, "FileUpload return object");
				return object;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.getErrorResult(e);
		} finally {
			if (uploadFile != null) {
				// 会在本地产生临时文件,用完后需要删除
				if (uploadFile.exists()) {
					FileUtil.del(uploadFile);
				}
			}
		}

	}


	@PostMapping("/deleteFile")
	@ApiOperation(value = "附件删除", notes = "附件删除", response = String.class)
	@ResponseBody
	public Object deleteFile(@RequestBody DeleteFileParam param) throws Exception {
		LogUtils.info(param, "deleteFile");
		try {
			if (param.getDbKey() == null) {
				ExceptionUtils.throwRuntimeException("上传DbKey为空");
			}

			List<String> IdList = param.getIdList();

			ObjectValidityUtils.checkNotEmpty(IdList, "删除文件ID");

			String[] ids = new String[IdList.size()];
			for (int i = 0; i < IdList.size(); i++) {
				ids[i] = IdList.get(i);
			}
//			
//			
//			String[] ids = ListUtils.listToArray(IdList);

			boolean flag = FileInfoService.delAttachByIds(param.getDbKey(), ids);

			if (flag) {
				Object object = ResultUtils.getSuccessResult("");
				LogUtils.info(object, "deleteFile return object");
				return object;
			} else {
				Object object = ResultUtils.getResult(false, "附件删除失败,请联系管理员!", JSON.toJSONString(""));
				LogUtils.info(object, "deleteFile return object");
				return object;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.getErrorResult(e);
		} finally {

		}
	}

	@PostMapping("/getFileList")
	@ApiOperation(value = "附件列表", notes = "附件列表", response = String.class)
	@ResponseBody
	public Object getFileList(@RequestBody GetFileListParam param) throws Exception {
		LogUtils.info(param, "getFileList");
		try {
			if (param.getDbKey() == null) {
				ExceptionUtils.throwRuntimeException("上传DbKey为空");
			}

			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFileList");

			Paging paging = loadDataServiceImpl.getPageData(sql, param.getDbKey(), param.getGetListParam());

			Object object = ResultUtils.getSuccessResult(paging);
			LogUtils.info(object, "getFileList return object");
			return object;

		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.getErrorResult(e);
		} finally {

		}
	}

//	@GetMapping("/getFile/{dbKey}/{id}")
//	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
//	@ResponseBody
//	public ResponseEntity<byte[]> getFile(
//			@ApiParam(name = "dbKey", value = "dbKey", required = true) @PathVariable String dbKey,
//			@ApiParam(name = "id", value = "附件id", required = true) @PathVariable String id) throws Exception {
//		LogUtils.info(id, "getFile");
//		try {
//			if (dbKey == null || dbKey.equals("") || dbKey.length() > 2) {
//				ExceptionUtils.throwRuntimeException("DbKey不合规则");
//			}
//
//			if (id == null || id.equals("")) {
//				ExceptionUtils.throwRuntimeException("文件id不合规则");
//			}
//
//			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
//			sql = sql.replaceAll("##id##", id);
//
//			List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapBySQL(sql);
//
//			if (mapList == null || mapList.size() == 0) {
//				return null;
//			}
//
//			String name = StringUtils.toNotNullString(mapList.get(0).get("file_name"));
//
//			HttpHeaders headers = new HttpHeaders();
//			String fileName = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
//			headers.setContentDispositionFormData("fileName", fileName);
//			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			FileInfoService.downloadById(dbKey, id, baos);
//
//			return new ResponseEntity(baos.toByteArray(), headers, HttpStatus.CREATED);
//		} catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		} finally {
//
//		}
//	}

	@GetMapping("/getFile/{dbKey}/{id}")
	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
	@ResponseBody
	public void getFile(@ApiParam(name = "dbKey", value = "dbKey", required = true) @PathVariable String dbKey,
			@ApiParam(name = "id", value = "附件id", required = true) @PathVariable String id) throws Exception {
		LogUtils.info(id, "getFile");
		try {
			if (dbKey == null || dbKey.equals("") || dbKey.length() > 2) {
				ExceptionUtils.throwRuntimeException("DbKey不合规则");
			}

			if (id == null || id.equals("")) {
				ExceptionUtils.throwRuntimeException("文件id不合规则");
			}

			String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
			sql = sql.replaceAll("##id##", id);

			List<Map<String, Object>> mapList = manageServ.getCommonServ(dbKey).getListMapBySQL(sql);

			if (mapList == null || mapList.size() == 0) {
				ExceptionUtils.throwRuntimeException("id == " + id + ",的文件不存在");
//				response.sendError(500, "id == " + id + ",的文件不存在");
//				return;
			}

			String name = StringUtils.toNotNullString(mapList.get(0).get("file_name"));
			
			String fileOutName = new String(name.getBytes("UTF-8"), "ISO8859-1");
			response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息
			

			FileInfoService.downloadById(dbKey, id, response.getOutputStream());

			response.getOutputStream().flush();
		} catch (Exception e) {
			e.printStackTrace();
			response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionTenLevel(e));// 设置头部信息
			response.sendError(200, "");
		} finally {

		}
	}


	@PostMapping("/getFiles")
	@ApiOperation(value = "附件下载", notes = "附件下载", response = String.class)
	@ResponseBody
	public void getFiles(@RequestBody GetFilesParam param) throws Exception {

		LogUtils.info(param, "param");
		ZipOutputStream zipOutputStream = null;
		File zipFile = null;

		BufferedInputStream bis = null;
		BufferedOutputStream out = null;
		FileInputStream in = null;

		try {
			if (param.getDbKey() == null) {
				ExceptionUtils.throwRuntimeException("DbKey为空");
//				response.sendError(500, "DbKey为空");
//				return;
			}

			List<String> IdList = param.getIdList();

			if (IdList == null || IdList.size() == 0) {
				ExceptionUtils.throwRuntimeException("文件ID列表为空");
//				response.sendError(500, "文件ID列表为空");
//				return;
			}
			
			if (IdList.size() >30) {
				ExceptionUtils.throwRuntimeException("文件个数大于30个");
//				response.sendError(500, "文件ID列表为空");
//				return;
			}

			ObjectValidityUtils.checkNotEmpty(IdList, "文件ID列表为空");
			
			String[] ids = new String[IdList.size()];
			
			for(int i= 0 ;i<IdList.size();i++) {
				ids[i] = IdList.get(i);
			}

//			String[] ids = ListUtils.listToArray(IdList);

			// =============
			String uuid = StringUtils.getUUID();
			String zipFileName = uuid + ".zip";

			String path = request.getSession().getServletContext().getRealPath("/");
			LogUtils.info(path, "path");

//			String zipPath = path + "userfiles/uploadFile/" + zipFileName;// 避免重复下载时读取旧文件
			String zipPath = path + zipFileName;// 避免重复下载时读取旧文件

			LogUtils.info(zipPath, "zipPath");

			// ----------
			zipFile = new File(zipPath); //
			zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));

			for (String pk : ids) {
				String sql = new BaseScanSqlCommand().getSqlText(this, "FileController.xml", "getFile");
				sql = sql.replaceAll("##id##", pk);

				List<Map<String, Object>> mapList = manageServ.getCommonServ(param.getDbKey()).getListMapBySQL(sql);

				if (mapList == null || mapList.size() == 0) {
					throw new RuntimeException(pk + "的数据信息不存在");
				}

				String DownAttachFileName = StringUtils.toNotNullString(mapList.get(0).get("file_name"));

				ByteArrayOutputStream outStream = new ByteArrayOutputStream();

				FileInfoService.downloadById(param.getDbKey(), pk, outStream);

				// ----------
				ZipEntry entry = new ZipEntry(DownAttachFileName);
				zipOutputStream.putNextEntry(entry);
				zipOutputStream.write(outStream.toByteArray(), 0, outStream.toByteArray().length);

				zipOutputStream.closeEntry();
			}

			zipOutputStream.close();// 记得关闭资源

			in = new FileInputStream(new File(zipPath));
			bis = new BufferedInputStream(in);
			out = new BufferedOutputStream(response.getOutputStream());

//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024 * 128];
			int n = -1;
			while ((n = bis.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}

			out.flush();
			
			

		} catch (Exception e) {
			e.printStackTrace();

//			if (zipOutputStream != null) {
//				zipOutputStream.close();
//			}
			if (zipFile != null) {
				boolean flag = zipFile.delete();
				LogUtils.info(flag, "zipFile delete flag");
				if (flag) {
					LogUtils.info("文件已删除(异常)", "");
				} else {
					LogUtils.info("文件未删除(异常)", "");
				}
			}
//			e.printStackTrace();
			response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionTenLevel(e));// 设置头部信息
			response.sendError(200, "");
		} finally {
			if (bis != null) {
				bis.close();
			}

			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
			
			if (zipOutputStream != null) {
				zipOutputStream.close();
			}
			
			boolean flag = zipFile.delete();
			LogUtils.info(flag, "zipFile delete flag");
			if (flag) {
				LogUtils.info("文件已删除", "");
			} else {
				LogUtils.info("文件未删除", "");
			}
		}
	}

}





分享到:
评论

相关推荐

    精通Spring MVC 4

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    Spring MVC jar包

    而`spring-framework-2.5.6-with-docs.zip`可能包含了Spring 2.5.6的源码和文档,帮助开发者了解Spring MVC的内部实现和最佳实践。 总之,这个压缩包提供了开发基于Spring MVC和Hibernate的Java Web应用所需要的...

    Spring MVC 文件上传下载 后端 - Java.zip

    这个压缩包文件"Spring MVC 文件上传下载 后端 - Java.zip"包含的文档可能详细阐述了如何在Java后端实现这些功能。以下是关于Spring MVC中文件上传和下载的关键知识点: 1. **Spring MVC 框架**:Spring MVC是...

    spring mvc 4.0

    Spring MVC是Spring框架的一个核心模块,专为构建Web应用程序提供模型-视图-控制器(MVC)架构。在Spring MVC 4.0版本中,它引入了许多改进和新特性,以提升开发效率和应用程序的性能。 1. **依赖注入**:Spring ...

    Spring mvc 教程

    - **Servlet 3.0 下的 MultipartResolver**:对于 Servlet 3.0 及以上版本,Spring MVC 提供了内置的文件上传支持。 - **处理表单中的文件上传**:通过控制器方法来接收和处理上传的文件。 #### 异常处理 ...

    spring-mvc-官方中文文档

    这个官方中文文档详细地介绍了如何使用 Spring MVC 来开发高效、可维护的 MVC(Model-View-Controller)架构的应用。Spring MVC 提供了丰富的功能,包括请求处理、视图解析、数据绑定、异常处理等,旨在简化 Web ...

    Spring MVC 4.2.4.RELEASE 中文文档

    Spring MVC提供了方便的文件上传和下载功能,开发者可以通过简单的API来实现复杂的文件操作。 **6. 异常处理** 通过自定义异常处理器,Spring MVC允许优雅地处理运行时异常,提供了统一的错误页面和异常信息。 **7...

    spring MVC .docx

    Spring MVC 是一个基于Java的轻量级Web应用框架,它是Spring框架的重要组成部分,主要...在提供的文档"spring MVC .docx"中,应该包含了关于这些知识点的详细解释和示例代码,帮助读者更好地理解和应用Spring MVC框架。

    spring mvc框架依赖全面jar

    在本压缩包中包含了一系列与Spring MVC相关的jar文件,这些文件是构建和运行Spring MVC项目所必需的依赖。 首先,`hibernate3.jar` 是Hibernate ORM框架的库,它允许开发者将Java对象映射到关系数据库,提供了数据...

    Spring MVC 入门实例

    在 Spring MVC 中, jsp 文件中尽量不要有 Java 代码, 只有 HTML 代码和"迭代(forEach)"与"判断(if)"两个jstl标签. jsp 文件只作为渲染(或称为视图 View)模板使用. 好了, 我们开始吧. 首先我们需要一个放在 WEB-INF...

    spring mvc demo下载地址

    Spring MVC 是一个基于Java的轻量级Web应用框架,它为构建模型-视图-控制器(Model-View-Controller)架构的应用程序提供了强有力的支持。这个简易的Spring MVC demo包含了一系列关键知识点,对于初学者来说是很好的...

    Spring MVC所需jar包

    6. **Apache Commons**:Spring MVC 开发中可能会用到 Apache Commons 的一些工具库,例如 `commons-logging.jar` 用于日志记录,`commons-fileupload.jar` 用于文件上传,`commons-lang3.jar` 提供了一些实用的 ...

    spring mvc文件上传实现进度条

    总的来说,实现Spring MVC文件上传的进度条功能需要前端和后端的紧密配合。前端负责用户交互和进度信息的显示,后端则需处理分块上传、进度跟踪和异步响应。通过这样的方式,我们可以在不阻塞用户界面的情况下,提供...

    精通Spring MVC4

    配置Spring MVC通常涉及web.xml文件中的DispatcherServlet配置,以及Spring配置文件中定义的Controller、ViewResolver和其他组件。Spring Boot简化了这一过程,通过自动配置和@SpringBootApplication注解可以快速...

    Spring MVC 教程快速入门 深入分析

    Spring MVC简单易用,可以快速提高开发效率,且性能优秀,社区活跃,文档丰富。由于支持注解配置,使得框架更加易用。相较于Struts2,Spring MVC避免了一些可能导致性能下降的特性,如值栈、OGNL表达式等。 二、...

    spring MVC文档

    这篇文档详细地介绍了Spring MVC的功能、工作原理以及如何将其有效地应用于实际项目中。Spring MVC的设计目标是提供一种简洁、可测试且灵活的方式来处理HTTP请求,并将这些请求映射到业务逻辑上,然后将结果呈现给...

    Spring MVC框架的各种依赖包下载

    通过下载提供的Spring MVC依赖包,你可以快速开始构建自己的Spring MVC项目,享受到Spring框架带来的强大功能和灵活性。记得正确配置项目结构,以及在pom.xml或build.gradle文件中引入所需的依赖,确保项目的顺利...

    Spring MVC 简单Demo

    - 在Spring MVC配置文件中声明处理器映射器、视图解析器、以及自定义的控制器等。 4. **创建简单示例** 在这个"Spring MVC 简单Demo"中,我们可能有一个名为`SummerWeb`的目录,其中包含以下文件: - `web.xml`...

Global site tag (gtag.js) - Google Analytics