SpringMVC文件上传

来源:互联网 发布:mac装win10多少钱 编辑:程序博客网 时间:2024/06/06 07:38
使用Spring_MVC有提供MultipartFile类来实现文件的上传。MultipartFile 提供了以下方法来操作上传的文件:
StringgetName(); //文件上传的name
StringgetOriginalFilename(); //文件名
StringgetContentType();
booleanisEmpty();
longgetSize();
byte[] getBytes() throws IOException;
InputStreamgetInputStream() throws IOException;
voidtransferTo(File dest) throws IOException,IllegalStateException;

实现文件上传需要用到两个jar包,一个是commons-fileupload ,另外一个是commons-io。
下面是一个文件上传的例子 (只列出了文件上传相关的):
1.导入jar包

2.在xml文件中配置文件上传类
<!--文件上传类--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
3.编写文件上传Controller
package com.cd.server.test;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.IOException;import java.util.UUID;@Controller@RequestMapping(value = "api/test")public class ApiTest {    private static final Logger logger = Logger.getLogger(ApiTest.class);    @RequestMapping(value = "/fileUpload")    public void fileUploadTest(            HttpServletRequest request,            HttpServletResponse response,           @RequestParam(value = "file" ,required = false) MultipartFile upFile            )    {        if(upFile == null)        {            System.out.println("no file upload");            return ;        }        //判断是否为空        if(upFile.isEmpty())        {            System.out.println("empty !!!");            return ;        }        //获得文件的上传名字       String fileName = upFile.getName();       System.out.println("fileName:" + fileName);       //获得文件名        String originalFilename = upFile.getOriginalFilename();        System.out.println("originalFilename:" + originalFilename);        //获得文件类型        String type = upFile.getContentType();        System.out.println("type:" + type);        //获得文件的大小        long size = upFile.getSize();        System.out.println("size:" + size);        //保存上传的文件        String path = request.getSession().getServletContext().getRealPath("/");        UUID uuid = UUID.randomUUID();  //生成一个随机数用来给文件命名        int index = originalFilename.lastIndexOf(".");        if(index > 0)        {            String savePath = path + uuid + originalFilename.substring(index);            System.out.println(savePath); //文件的保存路径            File targetFile = new File(savePath); //创建要保存的文件            if (!targetFile.exists())            {                targetFile.mkdirs();            }            try            {                upFile.transferTo(targetFile); //将上传的文件保存在本地            }            catch (IOException e)            {               logger.error(e);            }        }    }}
4.使用postman 测试

5.输出结果 :

   关于这个类的方法也有一个疑惑:boolean isEmpty();
官方的代码注释是 :
/** * Return whether the uploaded file is empty, that is, either no file has * been chosen in the multipart form or the chosen file has no content. */
但是当我不上传文件的时候使用这个方法会报空指针异常。


0 0