base64文件springmvc文件下载

1.进行数据请求

window.location.href=’’…/…/…/xx/export.do?id=x"

2.编写java代码

 @RequestMapping("/export")  
    public ResponseEntity<byte[]> export(HttpServletRequest req, String id) throws Exception {  
    //从数据库进行数据查询
	    Attach xx = new Attach();
		xx.setId(id);
		xx= xxService.getEntity(attach);

		String filepath = req.getServletContext().getRealPath("/upload/");//获取项目路径到webapp
    	
		File file=new File(filepath);
		//如果没有这个路径将自动创建
		if(!file.exists()){
		//并将文件放在指定的位置上
    		FileUtil.base64ToFile(filepath, attach.getAttach(), attach.getName());
    	}
    	//设置响应头信息
    	HttpHeaders headers = new HttpHeaders();    
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    
        headers.setContentDispositionFormData("attachment", attach.getName());   
        //将文件内容,状态码,响应头反馈至页面 
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filepath+"/"+(attach.getName()))),      headers, HttpStatus.CREATED);      } 

3.base64工具类

package com.ceair.util;

import java.io.*;
import java.util.Base64;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	/**
	 *
	 * @param path
	 * @return String
	 * @description 将文件转base64字符串
	 * @date 2018年3月20日
	 * @author changyl File转成编码成BASE64
	 */

	public static String fileToBase64(String path) {
		String base64 = null;
		InputStream in = null;
		try {
			File file = new File(path);
			in = new FileInputStream(file);
			byte[] bytes = new byte[(int) file.length()];
			in.read(bytes);
			base64 = Base64.getEncoder().encodeToString(bytes);
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return base64;
	}

	// BASE64解码成File文件
	public static void base64ToFile(String destPath, String base64,
			String fileName) {
		File file = null;
		// 创建文件目录
		String filePath = destPath;
		File dir = new File(filePath);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();
		}
		BufferedOutputStream bos = null;
		java.io.FileOutputStream fos = null;
		try {
			byte[] bytes = Base64.getDecoder().decode(base64);
			file = new File(filePath + "/" + fileName);
			fos = new java.io.FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
	}

	// byte生成File文件
	public static void byteToFile(String destPath, byte[] bytes, String fileName) {
		File file = null;
		// 创建文件目录
		String filePath = destPath;
		File dir = new File(filePath);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();
		}
		BufferedOutputStream bos = null;
		java.io.FileOutputStream fos = null;
		try {
			file = new File(filePath + "/" + fileName);
			fos = new java.io.FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
	}

	public static String uploadFile(HttpServletRequest request,
			MultipartFile file) {
		try {
			String path = request.getServletContext().getRealPath("upload");
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if ((file != null) && (!file.isEmpty())) {
				String oldName = file.getOriginalFilename();
				String ex = oldName.substring(oldName.lastIndexOf("."));
				String name = UUID.randomUUID().toString() + ex;
				File upload = new File(dir, name);
				file.transferTo(upload);
				return "/upload/" + name;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
}

猜你喜欢

转载自blog.csdn.net/cailizhu833/article/details/88787412