SpringMVC实现上传和下载

package com.pk.web.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
 

@Controller
@RequestMapping("file")
public class UploadController {
    @RequestMapping("/upload.do")
    public String upload(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
               // 这里我用到了jar包
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
 
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
 
                    String path1 = Thread.currentThread()
                            .getContextClassLoader().getResource("").getPath()
                            + "download" + File.separator;
 
                    //  下面的加的日期是为了防止上传的名字一样
                    String path = path1
                            + new SimpleDateFormat("yyyyMMddHHmmss")
                                    .format(new Date()) + fileName;
 
                    File localFile = new File(path);
 
                    file.transferTo(localFile);
                }
 
            }
 
        }
        return "uploadSuccess";
 
    }
    @RequestMapping("/toUpload.do")
    public String toUpload() {
        return "upload";
    }
 
    @RequestMapping("/download")
    public String download(String fileName, HttpServletRequest request,
            HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + fileName);
        try {
            String path = Thread.currentThread().getContextClassLoader()
                    .getResource("").getPath()
                    + "download";//这个download目录为啥建立在classes下的
            InputStream inputStream = new FileInputStream(new File(path
                    + File.separator + fileName));
 
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
 
             // 这里主要关闭。
            os.close();
 
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
            //  返回值要注意,要不然就出现下面这句错误!
            //java+getOutputStream() has already been called for this response
        return null;
    }
}

springmvc配置文件:

 <!-- mvc注解驱动 -->

    <mvc:annotation-driven/>

    <!-- 扫描器已经有了上面这个mvc注解驱动的功能了,所有不需要了 -->

    <context:component-scan base-package="com.pk.web.controller" />


    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <property name="defaultEncoding" value="utf-8" />

        <property name="maxUploadSize" value="104857600"/>

        <property name="maxInMemorySize" value="4096"/>

    </bean>




    <!-- 前缀+ viewName +后缀 -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- webroot到某一指定的文件夹的路径 -->

        <property name="prefix" value="/WEB-INF/jsp/"></property>

      <!--  自己在你的 /WEB-INF/jsp下建立给jsp见面吧。或者该我上面的配置 -->

        <!-- 视图名称的后缀 -->

        <property name="suffix" value=".jsp"></property>

    </bean>

web.xml配置文件:

<servlet>

        <servlet-name>springmvc</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <load-on-startup>1</load-on-startup>


    </servlet>


    <filter>

        <filter-name>encodingFilter</filter-name>

        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <init-param>

            <param-name>encoding</param-name>

            <param-value>UTF-8</param-value>

        </init-param>

        <init-param>

            <param-name>forceEncoding</param-name>

            <param-value>true</param-value>

        </init-param>

    </filter>


    <filter-mapping>

        <filter-name>encodingFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>


    <servlet-mapping>

        <servlet-name>springmvc</servlet-name>

        <!-- struts习惯使用/*,在springmvc不管用 -->

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>



测试页面代码:

这里是html 点击下载,这里就写死了(你可以修改成你自己放的文件)。可以修改的。

  <a href="file/download.do?fileName=map.txt">下载1 </a><br />

下面这里是上传代码

   <form action="file/upload.do" method="post" enctype="multipart/form-data">

            选择文件<input type="file" name="file">

            <input type="submit" value="上传">

        </form>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Spring MVC的文件上传下载功能,需要进行以下步骤: 1、引入Apache Commons FileUpload组件的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2、配置文件上传解析器。在Spring MVC的配置文件中,配置一个MultipartResolver的Bean用于处理文件上传请求。 3、创建文件上传的表单。在HTML表单中,设置enctype为"multipart/form-data",并添加一个文件选择框。 4、创建文件上传的控制器。在控制器中,使用MultipartFile参数接收上传的文件,并执行相应的操作,比如保存文件到指定位置。 5、创建文件下载的控制器。在控制器中,使用ResponseEntity<byte[]>对象来实现文件的下载,设置相应的响应头信息,如Content-Disposition和文件名。 下面是一个示例的代码,演示了如何实现文件上传下载: ``` // 文件上传的控制器 @Controller public class FileUploadController { @RequestMapping("/fileUpload") public String testFileUpload(MultipartFile photo, HttpSession session) throws IOException { String filename = photo.getOriginalFilename(); ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("photo"); File file = new File(realPath); if (!file.exists()) { file.mkdir(); } String finalPath = realPath + File.separator + filename; photo.transferTo(new File(finalPath)); return "success"; } } // 文件下载的控制器 @Controller public class FileDownloadController { @RequestMapping("/fileDownload") public ResponseEntity<byte[]> testFileDownload(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("static/img/a.jpg"); InputStream inputStream = new FileInputStream(realPath); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=a.jpg"); HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status); inputStream.close(); return responseEntity; } } // 文件上传的表单 <form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="photo" multiple> <input type="submit" value="上传"/> </form> ``` 通过以上步骤,你可以在Spring MVC实现文件的上传下载功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值