码迷,mamicode.com
首页 > 编程语言 > 详细

Java中资料的上传与下载

时间:2018-10-23 14:42:56      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:isp   coding   text   ora   except   pst   class   jpg   tco   

1.导架包

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

2.配置ssm.xml文件

<!--配置上传文件-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8"></property>
            <property name="maxUploadSize" value="#{10*1024*1024}"></property>
         </bean>
    <!--设置静态资源的访问-->
        <mvc:resources mapping="/upload/**" location="/upload/"></mvc:resources>
        <mvc:annotation-driven></mvc:annotation-driven>

3.前端提交上传表单

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

4.处理上传请求

 @RequestMapping("upload")
    public String addbook(MultipartFile myfile,HttpServletRequest request) {
        String path=request.getRealPath("/uploadimage");//要保存文件的文件夹
        try {
            myfile.transferTo(new File(path+"/"+myfile.getOriginalFilename()));//复制
        } catch (IOException e) {
            e.printStackTrace();
        }
        request.setAttribute("filename",myfile.getOriginalFilename());//return "redirect:/book/getbooklist";
    }

5.前端下载请求

<a href="down?fname=汪达尔.jpg">下载</a>

6.处理下载请求

@RequestMapping("down")
    public ResponseEntity down(HttpServletRequest request,String fname){
        String path = request.getRealPath("/upload");
        System.out.println(path);
        File f= new File(path+"/"+fname);
        HttpHeaders h =new HttpHeaders();
        h.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> res = null;
        try {
            h.setContentDispositionFormData("attachment", URLEncoder.encode(fname,"utf-8"));
            res = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f),h, HttpStatus.CREATED);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;
    }

 

Java中资料的上传与下载

标签:isp   coding   text   ora   except   pst   class   jpg   tco   

原文地址:https://www.cnblogs.com/yunshao/p/9835757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!