SpringMVC中使用 MultipartFile 进行文件上传下载及删除

一:引入必要的包

 <!--文件上传-->
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

二:在spring-service中配置

<!-- 支持上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>

三:文件上传

3.1 实现方法

  /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    public JSONObject uploadFile(MultipartFile file, HttpServletRequest request){
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //获取文件存放路径
        String path = request.getSession().getServletContext().getRealPath("").concat("/uploadFile");
       // String path = getUploadPath(fileName,request);
        //上传文件
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
            return resultErrorJson(fileName);
        }
        logger.info(fileName+"文件上传成功");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key","true");
        jsonObject.put("name",fileName);
        jsonObject.put("path",path+"/"+fileName);
        return jsonObject;
    }

3.2 controller层

  @RequestMapping(value="/upload")
    @ResponseBody
    public JSONObject upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
        fileOperation = new FileOperation();
        //返回文件后的文件路径
        return fileOperation.uploadFile(file,request);
    }

3.3 文本递交的时候 注意提交格式

  <form action="/file/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" value="提交">
        </form>

四:文件下载

 

/**
     * 下载文件
     * @param fileName 文件模板
     * HttpServletRequest request,
     * @param response response请求
     */
    public boolean download(String fileName,  HttpServletRequest request,HttpServletResponse response) {
        try {
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + fileName);
            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;
    }

五 删除文件

    /**
     * 通过文件绝对路径 删除单个文件
     * @param filePath
     */
    public boolean delFile(String filePath) {
        File delFile = new File(filePath);
        if(delFile.isFile() && delFile.exists()) {
            delFile.delete();
            logger.info("删除文件成功");
            return true;
        }else {
            logger.info("没有该文件,删除失败");
            return false;
        }
    }
原文地址:https://www.cnblogs.com/luffyu/p/6145086.html