SSM使用Multipartfile上传下载

Controller 上传//
//APIResult是封装好返回的code码
 
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	@ResponseBody
public APIResult upload(@RequestParam(value = "file") MultipartFile file,HttpServletRequest request, UploadAndDownl uploadAndDownl) {String path = null;try {request.setCharacterEncoding("utf-8");// 此处MultipartFile[]代表是多文件,若是是单文件MultipartFile就好了if (file.isEmpty()) {return this.setResult(ResultCode.E_102, "文件未上传");} else {// 获得上传的文件名String fileName = file.getOriginalFilename();String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());if (!fileType.equals("xls") && !fileType.equals("xlsx")) {return this.setResult(ResultCode.E_103, fileType);}// 获得服务器项目发布运行所在地址 path="d:/upload/tmpfile/a/"; /*path = "/opt/tomcat7/webapps/ROOT/tmpFile/";*/ * String path = * request.getSession().getServletContext().getRealPath * ("").concat( "/ROOT/tmpFile"); *//* file.transferTo(new File("d:/upload/",fileName)); */File targetPath = new File(path);File targetFile = new File(targetPath, fileName);// 找不到路径 会建立文件夹if (!targetPath.exists()) {targetPath.mkdirs();}file.transferTo(targetFile);// 文件转存}} catch (Exception e) {e.printStackTrace();return this.setResult(ResultCode.ERROR, e.getMessage());}}
 

下载 Class类html

public boolean download(String path,String fileDate, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("application/force-download");
			response.setCharacterEncoding("utf-8");
			String fileName=fileDate+".xls";
			response.setHeader("Content-Disposition", "attachment;fileName="
					+java.net.URLEncoder.encode(fileName, "UTF-8"));
			
			String  path = request.getSession().getServletContext().getRealPath("/")+
			  "/uploadFile/"+fileName;
			 
			File tempFile = new File(path);
			
            InputStream inputStream = new FileInputStream(tempFile);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}
			os.flush();
			os.close();
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件下载失败");
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件下载失败");
			return false;

		}
		return true;
	}

参考:http://www.cnblogs.com/luffyu/p/6145086.html