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

本文介绍了如何在SpringMVC框架中利用MultipartFile进行文件上传、下载和删除的操作。首先,文章提及了需要引入的相关依赖包。接着详细阐述了在服务层的配置,包括实现文件上传的方法、控制器层的处理以及前端递交时的格式要求。此外,还讲解了文件下载和删除的具体步骤。

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

一、引入必要的包

<!--文件上传-->
    <!-- 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">
    <inputtype="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;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值