UploadFiled.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<h2>文件上传</h2>
<form action="upload.do" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>文件描述:</td>
<td><input type="text" name="description"></td>
</tr>
<tr>
<td>请选择文件:</td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form>
</body>
</html>
控制器FileUploadController.class
package cn.upload.controller;
import java.io.File;
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.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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 cn.upload.domain.User;
@Controller
public class FileUploadController {
@RequestMapping("/UploadFiled")
public String s(){
System.out.println("==");
return "/UploadFiled";
}
// @ResponseBody @RequestParam("description") String description,
@RequestMapping(value="/upload",method=RequestMethod.POST)
public String upload(HttpServletRequest request,
@RequestParam("description")String description,
@RequestParam("file") MultipartFile file)throws Exception{
System.out.println("sddddd");
System.out.println(description);
//如果文件不为空,写入上传路径
if(!file.isEmpty()){
//上传文件路径
String path=request.getServletContext().getRealPath("/imag");
System.out.println(path);
String filename=file.getOriginalFilename();
File filepath=new File(path,filename);
//判断路径是否存在,如果不存在就创建一个
if(!filepath.getParentFile().exists()){
filepath.getParentFile().mkdirs();
}
//将上传的文件保存到目标文件中
file.transferTo(new File(path+File.separator+filename));
return "success";
}else{
return "error";
}
}
文件下载
@RequestMapping(value="/download")
public ResponseEntity<byte[]> down(HttpServletRequest request,
@RequestParam("filename") String filename,
Model model)throws Exception{
//下载路径
String path=request.getServletContext().getRealPath("/imag/");
File file=new File(path+File.separator+filename);
HttpHeaders headers=new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadfilename=new String(filename.getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment (下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadfilename);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
}