import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class One {
@RequestMapping(value="shang.do")
public String upload(MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
//如果是多文件上传的话就给个数组file【】然后给个for循环
//获取道上传的请求路径
String lu = request.getServletContext().getRealPath("/upload/");
//拿到上传的文件名
String name = file.getOriginalFilename();
//改名字,为什么要改名字:以防文件名字重复覆盖内容
//防止同一时间上传随机数值然后加上原来的文件名就是一个新的名字
String newname=new Date().getTime()+new Random().nextInt(99)+name;
//实例化file的对象去加载上传的路径和文件
//上传一个完整的文件路径
File f=new File(lu+newname);
//把完整的路径给写过去
//然后第一个抛出异常
file.transferTo(f);
//创建一个sess页面
return "sess";
}
@RequestMapping(value="dwnload.do")
public ResponseEntity<byte[]> two(@RequestParam("fileName") String fileName,HttpServletRequest requesst) throws IOException {
String nu = requesst.getServletContext().getRealPath("/dwnload/");
//实例化
File f=new File(nu+fileName);
//转换格式,报错抛出异常
String lewname = new String(fileName.getBytes("utf-8"),"iso8859-1");
//转流
HttpHeaders http = new HttpHeaders();
//attachment是固定格式
http.setContentDispositionFormData("attachment", lewname);
http.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//最后把他给相应发送过去,是个数组
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),http,HttpStatus.CREATED);
}
web.xml
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
applicationContext.xml配置文件设置
<!-- 文件上传的设置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxInMemorySize" value="102400000"></property>
</bean>