Spring实现文件上传功能

所属分类: 软件编程 / java 阅读数: 49
收藏 0 赞 0 分享

本篇文章,我们要来做一个Spring的文件上传功能:

1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖:

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-web</artifactId>

  <version>1.0.2.RELEASE</version>

</dependency> 

2.在webapp目录下的index.jsp文件中输入一个表单:

<html>

<body>

<form method="POST" enctype="multipart/form-data"

   action="/upload">

  File to upload: <input type="file" name="file"><br /> Name: <input

    type="text" name="name"><br /> <br /> <input type="submit"

                           value="Upload"> Press here to upload the file!

</form>

</body>

</html> 

这个表单就是我们模拟的上传页面。

3. 编写处理这个表单的Controller:

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;

 

@Controller

public class FileUploadController {

 

  @RequestMapping(value="/upload", method=RequestMethod.GET)

  public @ResponseBody String provideUploadInfo() {

    return "You can upload a file by posting to this same URL.";

  }

 

  @RequestMapping(value="/upload", method=RequestMethod.POST)

  public @ResponseBody String handleFileUpload(@RequestParam("name") String name,

      @RequestParam("file") MultipartFile file){

    if (!file.isEmpty()) {

      try {

        byte[] bytes = file.getBytes();

        BufferedOutputStream stream =

            new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));

        stream.write(bytes);

        stream.close();

        return "You successfully uploaded " + name + " into " + name + "-uploaded !";

      } catch (Exception e) {

        return "You failed to upload " + name + " => " + e.getMessage();

      }

    } else {

      return "You failed to upload " + name + " because the file was empty.";

    }

  }

 

} 

4. 然后我们对上传的文件做一些限制,同时编写main方法来启动这个web :

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.boot.context.embedded.MultiPartConfigFactory;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

 

import javax.servlet.MultipartConfigElement;

 

@Configuration

@ComponentScan

@EnableAutoConfiguration

public class Application {

 

  @Bean

  public MultipartConfigElement multipartConfigElement() {

    MultiPartConfigFactory factory = new MultiPartConfigFactory();

    factory.setMaxFileSize("128KB");

    factory.setMaxRequestSize("128KB");

    return factory.createMultipartConfig();

  }

 

  public static void main(String[] args) {

    SpringApplication.run(Application.class, args);

  }

} 

5. 然后访问http://localhost:8080/upload就可以看到页面了。

上面的例子是实现的是单个文件上传的功能,假定我们现在要实现文件批量上传的功能的话,我们只需要简单的修改一下上面的代码就行,考虑到篇幅的问题,下面只是贴出和上面不同的代码,没有贴出的说明和上面一样。:

1.  新增batchUpload.jsp文件

<html>

<body>

<form method="POST" enctype="multipart/form-data"

   action="/batch/upload">

  File to upload: <input type="file" name="file"><br />

  File to upload: <input type="file" name="file"><br />

  <input type="submit" value="Upload"> Press here to upload the file!

</form>

</body>

</html> 

2. 新增BatchFileUploadController.java文件:

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.MultipartHttpServletRequest;

 

import javax.servlet.http.HttpServletRequest;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.util.List;

 

/**

 * Created by wenchao.ren on 2014/4/26.

 */

 

@Controller

public class BatchFileUploadController {

 

  @RequestMapping(value="/batch/upload", method= RequestMethod.POST)

  public @ResponseBody

  String handleFileUpload(HttpServletRequest request){

    List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");

    for (int i =0; i< files.size(); ++i) {

      MultipartFile file = files.get(i);

      String name = file.getName();

      if (!file.isEmpty()) {

        try {

          byte[] bytes = file.getBytes();

          BufferedOutputStream stream =

              new BufferedOutputStream(new FileOutputStream(new File(name + i)));

          stream.write(bytes);

          stream.close();

        } catch (Exception e) {

          return "You failed to upload " + name + " => " + e.getMessage();

        }

      } else {

        return "You failed to upload " + name + " because the file was empty.";

      }

    }

    return "upload successful";

  }

} 

这样一个简单的批量上传文件的功能就ok了,是不是很简单啊。 

注意:上面的代码只是为了演示而已,所以编码风格上采取了随性的方式,不建议大家模仿。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java实现序列化与反序列化的简单示例

序列化与反序列化是指Java对象与字节序列的相互转换,一般在保存或传输字节序列的时候会用到,下面有两个Java实现序列化与反序列化的简单示例,不过还是先来看看序列和反序列化的具体概念:
收藏 0 赞 0 分享

以Java代码为例讲解设计模式中的简单工厂模式

简单来说,工厂模式就是按照需求来返回一个类型的对象,使用工厂模式的意义就是,如果对象的实例化与代码依赖太大的话,不方便进行扩展和维护,使用工厂的目的就是使对象的实例化与主程序代码就行解耦.来具体看一下:
收藏 0 赞 0 分享

Java线程池的几种实现方法及常见问题解答

下面小编就为大家带来一篇Java线程池的几种实现方法及常见问题解答。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Java线程池的几种实现方法和区别介绍

下面小编就为大家带来一篇Java线程池的几种实现方法和区别。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧,祝大家游戏愉快哦
收藏 0 赞 0 分享

深入理解Java 对象和类

下面小编就为大家带来一篇深入理解Java 对象和类。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅析Java编程中类和对象的定义

下面小编就为大家带来一篇浅析Java编程中类和对象的定义。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,祝大家游戏愉快哦
收藏 0 赞 0 分享

SpringMVC文件上传的配置实例详解

本文通过实例代码给大家介绍SpringMVC文件上传的配置相关内容,本文介绍的非常详细,具有参考借鉴价值,感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

java发送http请求并获取状态码的简单实例

下面小编就为大家带来一篇java发送http请求并获取状态码的简单实例。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解Java中格式化日期的DateFormat与SimpleDateFormat类

DateFormat其本身是一个抽象类,SimpleDateFormat 类是DateFormat类的子类,一般情况下来讲DateFormat类很少会直接使用,而都使用SimpleDateFormat类完成,下面我们具体来看一下两个类的用法:
收藏 0 赞 0 分享

Java使用设计模式中的工厂方法模式实例解析

当系统准备为用户提供某个类的子类的实例,又不想让用户代码和该子类形成耦合时,就可以使用工厂方法模式来设计系统.工厂方法模式的关键是在一个接口或抽象类中定义一个抽象方法,下面我们会具体介绍Java使用设计模式中的工厂方法模式实例解析.
收藏 0 赞 0 分享
查看更多