SSM框架文件上传与下载

一、文件上传

  • SpringMVC配置文件中添加
 <!-- 定义一个id为multipartResolver文件解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 文件上传的总大小 -->
        <property name="maxUploadSize" value="600000000"></property>
        <!-- 文件上传时每个文件的最大值 -->
        <property name="maxUploadSizePerFile" value="300000000"></property>
    </bean><!-- file size is limit -->
  • 包含文件的表单标签中加入属性
enctype="multipart/form-data"
  • 控制层创建MultipartFile对象,对象名与表单中file标签的name一致
  /**
     * 保存文件
     * @return
     */
    @RequestMapping("saveFile")
    public String saveFile(Attachment attachment, MultipartFile uploadfile){
        //获取原文件名以及,防止文件名称重复添加字段,并添加分隔符
              String filename = System.currentTimeMillis()+ "," + uploadfile.getOriginalFilename();

        //创建新的File对象保存文件路径
        File file = new File("/home/jingsongchan/HTMLTEST/upload", filename);
        //保存文件
        try {
            uploadfile.transferTo(file);
            //保存到数据库
            attachment.setPath(filename);
            attachment.setUploadtime(new Date());
            attachment.setUpdatetime(new Date());
            projectSerivice.saveFile(attachment);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:project-file";
    }

二、文件下载

  • ResponseEntity<byte[]>对象
    /**
     * 文件下载
     * @param id
     * @param path
     * @return
     * @throws IOException
     */
    @RequestMapping("attachmentDownload/{id}")
    public ResponseEntity<byte[]>  attachmentDownload(@PathVariable("id") String id, String path) throws IOException {
        //创建文件对象,文件路径
        File file = new File("/home/jingsongchan/HTMLTEST/upload", path);
        //获取原始文件名
        path = path.substring(path.indexOf(","));
        //创建响应头,添加附件名
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentDispositionFormData("attachment",path);
        //设置下载类型
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(
                FileUtils.readFileToByteArray(file),httpHeaders,HttpStatus.OK
        );
        return responseEntity;
    }

jingsongchan

发表评论

电子邮件地址不会被公开。 必填项已用*标注