zoukankan      html  css  js  c++  java
  • SpringMVC的上传和下载


    文件上传:

    一:单文件上传

      步骤如下:

      1.导入jar包

       

      2.书写控制器方法 获取到文件路径

      

      3.applicationContext大配置:

      

      4.绘制页面,进行渲染

      

      假如说现在测试项目的话,会出现一个问题:(500错误信息:无法实例化MultipartFile)

      

      解决方案:

      在大配置进行注解驱动的配置:

      

      

      我们进行单个文件上传后,会感觉不太严谨,想再规范限定一下它的文件类型,于是做了下面这个操作:

      通过后缀名控制文件上传的类型:

      

      进行一个判断,限定一下,还想到,假如说没有进行文件的上传,但是用户点击了上传按钮,会让他进入上传页面:

      

    二:多文件上传

      


    文件下载:

    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    
    @Controller
    public class MyController {
    
    	@RequestMapping("download.do")    
        public ResponseEntity<byte[]> download() throws IOException {    
            File file=new File("F:\Y2\OA\.metadata\.me_tcat\webapps\SpringMVC_fileupload\images\111.jpg");  
            HttpHeaders headers = new HttpHeaders();    
            String fileName=new String("你好.jpg".getBytes("utf-8"),"iso-8859-1");//为了解决中文名称乱码问题  
            headers.setContentDispositionFormData("attachment", fileName);   
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);    
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                              headers, HttpStatus.CREATED);    
        }    
    	
    }
    
    <form action="${pageContext.request.contextPath}/frist.do" method="post" enctype="multipart/form-data">
     			文件:<input type="file" name="uploadFile"/><br/>
     			    <input type="submit" value="上传"/>
     	</form> 
     	
     	<a href="${pageContext.request.contextPath}/download.do?111.jpg">下载</a>
     	
     	注解版配置欢迎你的使用~~~
    


  • 相关阅读:
    maven 项目 spring mvc + jdbc 配置文件
    (BUG已修改,最优化)安卓ListView异步加载网络图片与缓存软引用图片,线程池,只加载当前屏之说明
    listview图片错位
    Android在线更新 远程安装程序
    Android中Socket大文件断点上传
    如何用JAVA生成注册序列号
    php学习随记3
    Chrome改动浏览器User Agent
    andoid电阻触摸移植
    【有奖征资源,分享有内涵】贡献你的CSDN博文和下载资源,不断更新中
  • 原文地址:https://www.cnblogs.com/hq-123/p/6270398.html
Copyright © 2011-2022 走看看