进击的java(5) spring mvc 文件上传下载

本文详细介绍了使用Spring MVC进行文件上传与下载的操作,包括控制器、服务层和前端实现,涉及MultipartFile、HttpServletResponse等关键组件的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

###spring mvc 文件上传下载

####上传

  • 用MultipartFile来上传文件,上传到本地指定路径下

  • controller:

      @RequestMapping(value = "/upload")
      @ResponseBody
      public String upload(@RequestParam("file") MultipartFile file,
      	@RequestParam("type") Integer type, HttpServletRequest request,
      	HttpServletResponse response) {
    
      	Preconditions.checkNotNull(type);
      	Preconditions.checkNotNull(file);
      	Preconditions.checkArgument(file.getSize() < Constants.FILE_MAX_SIZE);
      	Preconditions.checkArgument(Constants.FILE_TYPE_MAP.containsKey(type));
    
      	if (!this.validate(file)) {
      		return JsonReply.newItem().failed().toJson();
      	}
    
      	String path = request.getSession().getServletContext().getRealPath("/");
    
      	Long fileId = fileService.saveFile(file, type, path);
    
      	if (fileId.equals(Constants.ERROR_LONG)) {
      		return JsonReply.newItem().failed().toJson();
      	}
    
      	JsonReply reply = JsonReply.newItem();
      	reply.addObject("id", fileId);
      	return reply.success().toJson();
    
      }
    

type是对类型做一个分类,不同类别放到不同文件夹下

  • service:

      @Override
      public Long saveFile(@NonNull MultipartFile multipartFile, Integer type,
      	String path) {
      	// TODO Auto-generated method stub
      	String originalName = multipartFile.getOriginalFilename();
    
      	// String fileDir = path + originalName;
      	String fileDir = Constants.FILE_DIR + Constants.FILE_TYPE_MAP.get(type)
      			+ originalName;
    
      	final File file = new File(fileDir);
      	try {
      		Files.write(multipartFile.getBytes(), file);
      	} catch (IOException e) {
      		// TODO: handle exception
      		log.info("save file error,{}", e);
      		return Constants.ERROR_LONG;
      	}
    
      	FileBo fileBo = new FileBo();
      	fileBo.setUrl(originalName);
      	fileBo.setType(type);
      	fileDao.saveFileInfo(fileBo);
      	return fileBo.getId();
    

    }

  • 前端:

      <body>
      <form id="form" method="post" action="./dundun-web/file/upload" enctype="multipart/form-data">                  
      <tr>  
          <td width="25%" align="right">上传文件:</td>  
          <td><input id="file" type="file" NAME="file" style="width:300px;"></td>  
      </tr>  
      <tr>
      	<label for="type" class="sr-only">类别</label>
          <input type="text" id="type" name="type" class="form-control" placeholder="类别" style="width:300px;">
      </tr>
      <br>
      <tr align="center" valign="middle">  
          <td height="60" colspan="2"><input type="submit" ID="BtnOK" value="确认上传"></td>  
      </tr>  
      </form>  
    
      <!-- Bootstrap core JavaScript
      ================================================== -->
      <!-- Placed at the end of the document so the pages load faster -->
      <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
      <script src="http://cdn.bootcss.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
      </body>
    

#####下载

  • 用HttpServletResponse来下载,但是不是最好的选择,今后改

  • controller:

      @RequestMapping(value = "/download/{id}")
      public void file(@PathVariable Long id, HttpServletResponse resp)
      	throws IOException {
    
      	OutputStream output = resp.getOutputStream();
    
      	Preconditions.checkNotNull(id);
    
      	FileBo file = fileService.getFileBo(id);
      	if (file == null) {
      		return;
      	}
      	String disposition = "attachment;filename=" + file.getUrl();
      	resp.reset();
      	resp.setHeader("Content-Disposition", disposition);
      	resp.setContentType("application/octet-stream; charset=utf-8");
    
      	try {
      		fileService.download(file, output);
      	} catch (IOException e) {
      		// TODO: handle exception
      		log.info("FileController.file failed.[{e}]", e);
      	} finally {
      		IOUtils.closeQuietly(output);
      	}
      }
    
  • service

      @Override
      public void download(FileBo file, OutputStream output) throws IOException {
      	// TODO Auto-generated method stub
    
      	String fileDir = Constants.FILE_DIR
      			+ Constants.FILE_TYPE_MAP.get(file.getType()) + file.getUrl();
    
      	final File downloadFile = new File(fileDir);
    
      	output.write(FileUtils.readFileToByteArray(downloadFile));
    
      }
    

转载于:https://my.oschina.net/SearchVera/blog/468861

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值