MultipartFile.getOriginalFilename()空指针异常,springMVC文件上传

出现空指针
第一看先看表单的method是不是post请求,文件上传只能在post表单中进行

第二看表单上传的参数name与方法中MultipartFile的参数名是否一致,或者使用 @RequestParam(value=“upload”,required=false) MultipartFile upload

第三看文件上传解析器的id值是否配置

基本三个中出现一个错误都会导致空指针异常

上传到的路径:
1)war模式这种可以称之为是发布模式,看名字也知道,这是先打成war包,再发布;
(2)war exploded模式是直接把文件夹、jsp页面 、classes等等移到Tomcat 部署文件夹里面,进行加载部署。因此这种方式支持热部署,一般在开发的时候也是用这种方式。//即上传到target包中

我tomcat部署的war包方式,所以上传的文件导入到了tomcat服务器webapps文件夹中,要定义虚拟目录,否则可能找不到上传的文件和文件夹

文件上传步骤:
1.导入commons-fileupload和commons-io的jar包
2.springmvc的xml中配置,使用mvc:resources为了访问静态资源

<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"></property>
    </bean>

jsp代码部分:

<head>
    <title>Title</title>
    <script src="js/jquery-3.5.0.min.js"></script>
</head>
<body>
    <form method="post" action="user/fileUpload" enctype="multipart/form-data">//必须的设置
        选择文件:<input type="file" name="upload" />
        <input type="submit" value="上传" />
    </form>
</body>

java代码部分:

package com.wz;

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.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class HelloFirst {

    @RequestMapping(value = "/fileUpload" ,method = RequestMethod.POST)
    public String uploadFile(HttpServletRequest request,
                             @RequestParam(value="upload",required=false) MultipartFile upload) throws IOException {
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断是否存在该文件夹,无则创建
        File file = new File(path);
        if(!file.exists()){
            file.mkdir();
        }

        //获取文件名称
        String filename = upload.getOriginalFilename();
        //把文件名称变成唯一值
        String  uuid = UUID.randomUUID().toString().replace("-","");
        filename = uuid+"_"+filename;
        //完成文件上传
        upload.transferTo(new File(path,filename));
        return "success";
    }
}

发布了43 篇原创文章 · 获赞 2 · 访问量 979

猜你喜欢

转载自blog.csdn.net/study_azhuo/article/details/105615069