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类

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值