java中文件流实现上传多个文件
//文件下载控制类
package com.zjn.IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DownController {
@RequestMapping(value = "/download")
public String download(HttpServletResponse response, Model model,String files) throws Exception {
System.out.println("进入文件下载》》》》》》》》》》》》》》》》》》files==="+files);
files = new String(files.getBytes("iso8859-1"),"UTF-8");//将iso8859-1编码换成utf-8
System.out.println("转码后files===="+files);
//通过文件名找出文件的所在目录
String URL = "D:\\whupload\\"+files;
//得到要下载的文件
File file = new File(URL);
//如果文件不存在
if(!file.exists()){
//如果文件不存在,进行处理
int i=1/0;//系统会报错,除数不能为0.
// return "modules/cms/front/themes/"+site.getTheme()+"/frontError";
}
InputStream inputStream = null;
OutputStream outputStream = null;
//创建缓冲区
byte[] b= new byte[1024];
int len = 0;
try {
//读取要下载的文件,保存到文件输入流
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
response.setContentType("application/force-download");
String filename = file.getName();
//设置响应头,控制浏览器下载该文件
response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentLength( (int) file.length( ) );
//循环将输入流中的内容读取到缓冲区当中
while((len = inputStream.read(b)) != -1){
//输出缓冲区的内容到浏览器,实现文件下载
outputStream.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(inputStream != null){
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(outputStream != null){
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
//文件上传实体类
package com.zjn.IO;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/testup")
public class UploadController {
/**
* 9.②多个文件上传
*/
@RequestMapping(value="/uploadBatchFile",method=RequestMethod.POST,consumes="multipart/form-data")
public String uploadBatchFile(@RequestParam MultipartFile[] files,RedirectAttributes redirectAttributes){
boolean isEmpty=true;
try {
for (MultipartFile multipartFile : files) {
if(multipartFile.isEmpty()){
continue;
}
String time=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String fileName=multipartFile.getOriginalFilename();
String destFileName="D:\\whupload"+File.separator+time+"_"+fileName;
File destFile=new File(destFileName);
multipartFile.transferTo(destFile);
isEmpty=false;
}
//int i=1/0;
//localhost:8086/test/index?message=upload file success
//redirectAttributes.addAttribute("message","upload file success.");
} catch (Exception e) {
// TODO Auto-generated catch block
redirectAttributes.addFlashAttribute("message", "文件上传失败");
System.out.println(e.getMessage());
return "redirect:message.do";
}
if(isEmpty){
redirectAttributes.addFlashAttribute("message", "上传文件为空");
}else{
redirectAttributes.addFlashAttribute("message", "文件上传成功");
}
return "redirect:message.do";
}
@RequestMapping("/message")
public String message() {
return "message";
}
/**
* @Method: makeFileName
* @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称
* @param filename 文件的原始名称
* @return uuid+"_"+文件的原始名称
*/
private String makeFileName(String filename){ //2.jpg
//为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
return UUID.randomUUID().toString() + "_" + filename;
}
}
// jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/testup/uploadBatchFile.do" method="post" enctype="multipart/form-data">
<input type="file" name="files">
<input type="file" name="files">
<button type="submit">上传</button>
</form>
<form action="${pageContext.request.contextPath}/download.do" method="post">
<input name="files" value="SAP接口说明V2.0(1).xlsx">
<button type="submit">下载</button>
</form>
</body>
</html>
<!--文件上传下载所用的包============ -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
//web文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<listener>
<listener-class>com.zjn.oneLogin.dengLu.MyListener</listener-class>
</listener>
</web-app>
//springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
<context:component-scan base-package="com.zjn" />
<!-- 这两个类用来启动基于Spring MVC的注解功能,将控制器与方法映射加入到容器中 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<!-- 这个类用于Spring MVC视图解析 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean>
<!-- 支持上传文件 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- 100M -->
<property name="maxUploadSize" value="10485760000"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
<!-- 数据库配置-->
<!-- 使用配置文件 -->
<context:property-placeholder location="classpath:properties/mysql.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 连接池最大使用连接数 -->
<property name="maxActive" value="20"/>
<!-- 初始化连接大小 -->
<property name="initialSize" value="1"/>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000"/>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="3"/>
<!-- 自动清除无用连接 -->
<property name="removeAbandoned" value="true"/>
<!-- 清除无用连接的等待时间 -->
<property name="removeAbandonedTimeout" value="180"/>
<!-- 连接属性 -->
<property name="connectionProperties" value="clientEncoding=UTF-8"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--指定实体类映射文件,可以指定同时指定某一包以及子包下面的所有配置文件 -->
<property name="mapperLocations" value="classpath:mapper/**/*.xml"/>
<!--mybatis全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- spring与mybatis整合配置,扫描所有dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zjn.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
// properties 文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/peixian jdbc.username=root jdbc.password=123456


浙公网安备 33010602011771号