文件上传下载

pom.xml

		<!-- 上传下载 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>

spring.xml配置

	<!-- 上传下载 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--配置上传文件 -->
		<property name="defaultEncoding" value="utf-8" /><!--默认字符编码 -->
		<property name="maxUploadSize" value="10485760000" /><!--上传文件大小 -->
		<property name="maxInMemorySize" value="4096" /><!--内存中的缓存大小 -->
	</bean>

文件上传

  1. 前端
<form method="post" action="upload.do" enctype="multipart/form-data">
	<input type="file" name="fileName" />
</form>
  1. 后台
	public static String upload(HttpServletRequest request) throws IOException {
		//1.转化request为:MultipartHttpServletRequest
		MultipartHttpServletRequest mhsRequest = (MultipartHttpServletRequest) request;
		//2.获取上传文件
		CommonsMultipartFile cmFile = (CommonsMultipartFile) mhsRequest.getFile("fileName");
		//3.获取上传文件的字节数组
		byte[] fileByte = cmFile.getBytes();
		//4.获取上传文件名
		String oldFileName = cmFile.getOriginalFilename();
		//存储文件的物理路径
		String uploadPath = "C:\\File\\";
		String url = uploadPath + oldFileName;
		OutputStream os;
		os = new FileOutputStream(url);
		os.write(fileByte);
		os.flush();
		os.close();
		return url;
	}

文件下载

  1. 前端
    将该文件的相关的信息传递到后台即可。
  2. 后台
    根据前台的相关信息得到该文件的路径,传入路径参数执行下载方法
	public static void download(HttpServletResponse response,String url) {
		//截取字符串,获取文件名
		int i = 24;
		String filename = url.substring(i);
		//获取输入流
		try {
			InputStream bis = new BufferedInputStream(new FileInputStream(new File(url)));
			//假如以中文名下载的话,转码以免文件名中文乱码
			filename = URLEncoder.encode(filename,"UTF-8");
			//设置文件下载头
			response.addHeader("Content-Disposition", "attachment;filename=" + filename);
			//设置文件ContentType类型,这样设置,会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			int len = 0;
			while((len = bis.read()) != -1) {
				out.write(len);
				out.flush();
			}
			out.close();
			bis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章