Java中资料的上传与下载

Posted 云飞九天

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中资料的上传与下载相关的知识,希望对你有一定的参考价值。

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中资料的上传与下载的主要内容,如果未能解决你的问题,请参考以下文章

java Ftp上传创建多层文件的代码片段

Java项目中的下载 与 上传

我的代码库-Java8实现FTP与SFTP文件上传下载

java文件上传与下载

用于从 cloudkit 检索单列的代码模式/片段

性能工具之 JMeter 上传与下载脚本编写