Springmvc实现文件上传下载

文件上传

springmvc中文件上传需要的第三方包主要有commons-fileupload.jar、commons-io.jar和spring-web.jar。其实现方式代码如下:

/**
 * @param request 请求对象
 * @param storePath 存储目录(文件夹)
 * @return boolean 是否上传成功
 * @throws IllegalStateException
 * @throws IOException
 * @description 参数不允许为空
 */
public static boolean upload(HttpServletRequest request, String storePath) throws IllegalStateException, IOException{
	 //创建一个通用的多部分解析器.     
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	//判断 request 是否有文件上传,即多部分请求
	if(multipartResolver.isMultipart(request)){
		//转换成多部分request    
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
		//取得request中的所有文件名  
		Iterator iterator = multiRequest.getFileNames(); 
		while(iterator.hasNext()){
			MultipartFile file = multiRequest.getFile(iterator.next());
			//获取上传文件的文件名
			String finaName = file.getOriginalFilename();
			String path = "";
			if(storePath.endsWith(File.separator)){
				path  += storePath + File.separator + finaName;
			}else{
				path += storePath + finaName;
			}
			file.transferTo(new File(path));
		}
		return true;
	}
	return false;
}

 

文件下载

文件下载用JDK自带jar即可,其代码如下:

/**
 * @Description:默认文件名下载方法(参数不允许为空)
 * @param response 相应对象
 * @param filePath 文件路径
 * @throws IOException
 */
public static void download(HttpServletResponse response,String filePath) throws Exception{
	 File file = new File(filePath);
	 if(file.isFile()){
		 download(response, file.getName(), filePath);
	 }else{
		 throw new Exception("下载类型不是文件或不存在!");
	 }
}

/**
 * @Description:自定义下载文件名方法(参数不允许为空)
 * @param response 相应对象
 * @param downloadName 下载文件名
 * @param filePath 文件路径
 * @throws IOException
 */
public static void download(HttpServletResponse response, String downloadName, String filePath) throws Exception{
	File file = new File(filePath);
	if(file.isFile()){
		long fileLength = file.length();
		String filaname = new String(downloadName.getBytes("gb2312"),"ISO8859-1");
		// 清空response  
		response.reset();
		response.setContentType("application/octet-stream;charset=ISO8859-1");
		response.setHeader("Content-Disposition","attachment;filename=\"" + filaname + "\"");
		response.setHeader("Content-Length", String.valueOf(fileLength));
		InputStream is = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		byte[] b = new byte[2048];  
		while (is.read(b) != -1) {
			os.write(b);
		}
		is.close();
		os.flush();
		os.close();
	}else{
		throw new Exception("下载类型不是文件或不存在!");
	}
}

 

你可能感兴趣的:(Java框架)