Java 使用SpringMVC和MockMVC上传文件

Java 使用SpringMVC和MockMVC上传文件,java,spring,mockmvc,Java,Spring,Mockmvc,我已成功地将图像文件上载到WebContent\resources\uploads\image.jsp。但是我在使用MockMvc测试时遇到了一个问题。当我运行测试用例时,我发现异常文件未找到,访问被拒绝 控制器如下所示: @RequestMapping(value="/AddContacts", method=RequestMethod.POST) public @ResponseBody String addContacts(ContactBean cb,HttpServletReq

我已成功地将图像文件上载到
WebContent\resources\uploads\image.jsp
。但是我在使用MockMvc测试时遇到了一个问题。当我运行测试用例时,我发现异常文件未找到,访问被拒绝

控制器如下所示:

@RequestMapping(value="/AddContacts", method=RequestMethod.POST)
    public @ResponseBody String addContacts(ContactBean cb,HttpServletRequest request,HttpServletResponse response,@RequestParam("upload") MultipartFile file) throws IllegalStateException, IOException 
    {

        String error=cb.validate();
        if(error.equals("")){
            Model m=new Model();
            String ret=m.addData(cb);
            System.out.println("Contact Bean: "+cb);
            if(ret.equals("DBFAIL")){
                response.setStatus(500);
            }
            else if(ret.equals("EXIST")){
                response.setStatus(409);
            }
            else{
                response.setStatus(200);
                /* to upload a file */
                if(file != null && file.getSize() > 0){
                    System.out.println("File name: "+file.getOriginalFilename());
                    String dir="C:\\web_latest\\Admin_FileUpload_29_01_15\\WebContent\\resources\\uploads\\"+cb.getName()+"_"+cb.getId()+"\\";
                    //String dir="C:\\Upload\\"+cb.getName()+"_"+cb.getId()+"\\";
                    File directory = new File(dir);
                    if (directory.exists()) {
                        System.out.println("Directory already exists ...");

                    } 
                    else {
                        System.out.println("Directory not exists, creating now");
                        boolean success = directory.mkdir();
                        if (success) {
                            System.out.printf("Successfully created new directory : %s%n", dir);
                        } 
                        else {
                            System.out.printf("Failed to create new directory: %s%n", dir);
                        }
                    }
                    String fileName = file.getOriginalFilename();
                    file.transferTo(new File(dir+fileName));
                }
            }
            return error;
        }
        else{
            //response.setStatus(500);
            return error;
        }

    }
public void testAddContacts() throws Exception {
    FileInputStream fis=new FileInputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
    //MockMultipartFile upload = new MockMultipartFile("upload", "Penguins.jpg", "image/jpeg", "C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg\\".getBytes());

    MockMultipartFile upload= new MockMultipartFile("upload",fis);
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
      mockMvc.perform(MockMvcRequestBuilders.fileUpload("/AddContacts")
              .file(upload)
              .param("some-random", "4")
              .param("name","deerdad")
              .param("email","niharik@gmail.com")
              .param("phone", "1234567890"))
          .andExpect(status().is(200));
}
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.servletContext.contextPath}/resources/css/form.css">
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery-1.11.1.js"></script>

        <script>


        function doAdd() {
        // get the form values
        var name = $('#name').val();
        var email = $('#email').val();
        var phone = $('#phone').val();

        var file = document.getElementById("uploadfile");
        var formData = new FormData();
        formData.append("upload", file.files[0]);
        formData.append("name",$('#name').val());
        formData.append("email",$('#email').val());
        formData.append("phone",$('#phone').val());


        $.ajax({
            type: "POST",
            url: "AddContacts",
            data: formData,
            processData: false,
            contentType: false,
            success: function(response){
                       $("#error").text("");
                       if(response==""){
                           $("#info").text("successfully added");
                           $('#myTable').append("<tr><td><input type='checkbox' name='cb' value='"+ response+"'><td>"+name + "</td><td>"+email + "</td><td>"+phone + "</td></tr>");
                           $("#addForm").hide();
                       }
                       else{
                           $("#info").text(response);
                       }
                  },
            error: function(){
                $("#info").text("");
                $("#error").text("Internal server error");
            },    
            statusCode: {
                        409: function(response,statusText) {
                            $("#info").text("");
                            $("#error").text("Name already exists ["+response.statusText+"]");
                        },
                        500: function(response,statusText) {
                            $("#info").text("");
                            $("#error").text("database problem ["+response.statusText+"]");
                        }
                      }
        });
        }
        </script>

    </head>
    <body bgcolor="FFFFCC">
        <center>
            <form:form action="" method="post" name="addForm" id="ufile" modelAttribute="upload" class="dark-matter">
                <h1>
                    Add Contacts <span>Please fill all the texts in the fields</span>
                </h1>
                <p>
                    <label> 
                        <input id="id" type="hidden">
                    </label> 
                    <label> 
                        <span>Your Name</span> 
                        <input id="name" type="text" name="name" placeholder="Your Full Name">
                    </label> 
                    <label> 
                        <span>Your Email</span> 
                        <input id="email" type="text" name="email" placeholder="Your Email">
                    </label> 
                    <label> 
                        <span>Your Phone</span> 
                        <input id="phone" type="text" name="phone" placeholder="Your phone">
                    </label>
                    <label>
                        <span>Upload Photo</span>
                        <input type="file" id="uploadfile" accept="image/*" name="uploadfile">              
                    </label>
                    <label> 
                        <span>&nbsp;</span> 
                        <input type="button" class="button"  id="btn" value="Add Me" onclick="doAdd()">
                    </label>
                </p>
            </form:form>
            <!--
            <div STYLE="color: #FF3333; background-color: #8888ff; width: 100px; border-radius: 10px; cursor: pointer;" id="sub">
                Add Me
            </div>
            -->
            <!--
            <input type="hidden" id="id" >
                <br/>
                Name : <input type="text" id="name"><br/><br/>
                Email : <input type="text" id="email"><br/><br/>
                Phone : <input type="text" id="phone"><br/><br/>
            <input type="button" value="Add Me" onclick="doAdd()">
            <br/>
            -->
        </center>
    </body>
</html>
我的测试用例如下所示:

@RequestMapping(value="/AddContacts", method=RequestMethod.POST)
    public @ResponseBody String addContacts(ContactBean cb,HttpServletRequest request,HttpServletResponse response,@RequestParam("upload") MultipartFile file) throws IllegalStateException, IOException 
    {

        String error=cb.validate();
        if(error.equals("")){
            Model m=new Model();
            String ret=m.addData(cb);
            System.out.println("Contact Bean: "+cb);
            if(ret.equals("DBFAIL")){
                response.setStatus(500);
            }
            else if(ret.equals("EXIST")){
                response.setStatus(409);
            }
            else{
                response.setStatus(200);
                /* to upload a file */
                if(file != null && file.getSize() > 0){
                    System.out.println("File name: "+file.getOriginalFilename());
                    String dir="C:\\web_latest\\Admin_FileUpload_29_01_15\\WebContent\\resources\\uploads\\"+cb.getName()+"_"+cb.getId()+"\\";
                    //String dir="C:\\Upload\\"+cb.getName()+"_"+cb.getId()+"\\";
                    File directory = new File(dir);
                    if (directory.exists()) {
                        System.out.println("Directory already exists ...");

                    } 
                    else {
                        System.out.println("Directory not exists, creating now");
                        boolean success = directory.mkdir();
                        if (success) {
                            System.out.printf("Successfully created new directory : %s%n", dir);
                        } 
                        else {
                            System.out.printf("Failed to create new directory: %s%n", dir);
                        }
                    }
                    String fileName = file.getOriginalFilename();
                    file.transferTo(new File(dir+fileName));
                }
            }
            return error;
        }
        else{
            //response.setStatus(500);
            return error;
        }

    }
public void testAddContacts() throws Exception {
    FileInputStream fis=new FileInputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
    //MockMultipartFile upload = new MockMultipartFile("upload", "Penguins.jpg", "image/jpeg", "C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg\\".getBytes());

    MockMultipartFile upload= new MockMultipartFile("upload",fis);
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
      mockMvc.perform(MockMvcRequestBuilders.fileUpload("/AddContacts")
              .file(upload)
              .param("some-random", "4")
              .param("name","deerdad")
              .param("email","niharik@gmail.com")
              .param("phone", "1234567890"))
          .andExpect(status().is(200));
}
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.servletContext.contextPath}/resources/css/form.css">
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery-1.11.1.js"></script>

        <script>


        function doAdd() {
        // get the form values
        var name = $('#name').val();
        var email = $('#email').val();
        var phone = $('#phone').val();

        var file = document.getElementById("uploadfile");
        var formData = new FormData();
        formData.append("upload", file.files[0]);
        formData.append("name",$('#name').val());
        formData.append("email",$('#email').val());
        formData.append("phone",$('#phone').val());


        $.ajax({
            type: "POST",
            url: "AddContacts",
            data: formData,
            processData: false,
            contentType: false,
            success: function(response){
                       $("#error").text("");
                       if(response==""){
                           $("#info").text("successfully added");
                           $('#myTable').append("<tr><td><input type='checkbox' name='cb' value='"+ response+"'><td>"+name + "</td><td>"+email + "</td><td>"+phone + "</td></tr>");
                           $("#addForm").hide();
                       }
                       else{
                           $("#info").text(response);
                       }
                  },
            error: function(){
                $("#info").text("");
                $("#error").text("Internal server error");
            },    
            statusCode: {
                        409: function(response,statusText) {
                            $("#info").text("");
                            $("#error").text("Name already exists ["+response.statusText+"]");
                        },
                        500: function(response,statusText) {
                            $("#info").text("");
                            $("#error").text("database problem ["+response.statusText+"]");
                        }
                      }
        });
        }
        </script>

    </head>
    <body bgcolor="FFFFCC">
        <center>
            <form:form action="" method="post" name="addForm" id="ufile" modelAttribute="upload" class="dark-matter">
                <h1>
                    Add Contacts <span>Please fill all the texts in the fields</span>
                </h1>
                <p>
                    <label> 
                        <input id="id" type="hidden">
                    </label> 
                    <label> 
                        <span>Your Name</span> 
                        <input id="name" type="text" name="name" placeholder="Your Full Name">
                    </label> 
                    <label> 
                        <span>Your Email</span> 
                        <input id="email" type="text" name="email" placeholder="Your Email">
                    </label> 
                    <label> 
                        <span>Your Phone</span> 
                        <input id="phone" type="text" name="phone" placeholder="Your phone">
                    </label>
                    <label>
                        <span>Upload Photo</span>
                        <input type="file" id="uploadfile" accept="image/*" name="uploadfile">              
                    </label>
                    <label> 
                        <span>&nbsp;</span> 
                        <input type="button" class="button"  id="btn" value="Add Me" onclick="doAdd()">
                    </label>
                </p>
            </form:form>
            <!--
            <div STYLE="color: #FF3333; background-color: #8888ff; width: 100px; border-radius: 10px; cursor: pointer;" id="sub">
                Add Me
            </div>
            -->
            <!--
            <input type="hidden" id="id" >
                <br/>
                Name : <input type="text" id="name"><br/><br/>
                Email : <input type="text" id="email"><br/><br/>
                Phone : <input type="text" id="phone"><br/><br/>
            <input type="button" value="Add Me" onclick="doAdd()">
            <br/>
            -->
        </center>
    </body>
</html>
我的jsp文件如下所示:

@RequestMapping(value="/AddContacts", method=RequestMethod.POST)
    public @ResponseBody String addContacts(ContactBean cb,HttpServletRequest request,HttpServletResponse response,@RequestParam("upload") MultipartFile file) throws IllegalStateException, IOException 
    {

        String error=cb.validate();
        if(error.equals("")){
            Model m=new Model();
            String ret=m.addData(cb);
            System.out.println("Contact Bean: "+cb);
            if(ret.equals("DBFAIL")){
                response.setStatus(500);
            }
            else if(ret.equals("EXIST")){
                response.setStatus(409);
            }
            else{
                response.setStatus(200);
                /* to upload a file */
                if(file != null && file.getSize() > 0){
                    System.out.println("File name: "+file.getOriginalFilename());
                    String dir="C:\\web_latest\\Admin_FileUpload_29_01_15\\WebContent\\resources\\uploads\\"+cb.getName()+"_"+cb.getId()+"\\";
                    //String dir="C:\\Upload\\"+cb.getName()+"_"+cb.getId()+"\\";
                    File directory = new File(dir);
                    if (directory.exists()) {
                        System.out.println("Directory already exists ...");

                    } 
                    else {
                        System.out.println("Directory not exists, creating now");
                        boolean success = directory.mkdir();
                        if (success) {
                            System.out.printf("Successfully created new directory : %s%n", dir);
                        } 
                        else {
                            System.out.printf("Failed to create new directory: %s%n", dir);
                        }
                    }
                    String fileName = file.getOriginalFilename();
                    file.transferTo(new File(dir+fileName));
                }
            }
            return error;
        }
        else{
            //response.setStatus(500);
            return error;
        }

    }
public void testAddContacts() throws Exception {
    FileInputStream fis=new FileInputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
    //MockMultipartFile upload = new MockMultipartFile("upload", "Penguins.jpg", "image/jpeg", "C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg\\".getBytes());

    MockMultipartFile upload= new MockMultipartFile("upload",fis);
    MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
      mockMvc.perform(MockMvcRequestBuilders.fileUpload("/AddContacts")
              .file(upload)
              .param("some-random", "4")
              .param("name","deerdad")
              .param("email","niharik@gmail.com")
              .param("phone", "1234567890"))
          .andExpect(status().is(200));
}
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.servletContext.contextPath}/resources/css/form.css">
    <script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery-1.11.1.js"></script>

        <script>


        function doAdd() {
        // get the form values
        var name = $('#name').val();
        var email = $('#email').val();
        var phone = $('#phone').val();

        var file = document.getElementById("uploadfile");
        var formData = new FormData();
        formData.append("upload", file.files[0]);
        formData.append("name",$('#name').val());
        formData.append("email",$('#email').val());
        formData.append("phone",$('#phone').val());


        $.ajax({
            type: "POST",
            url: "AddContacts",
            data: formData,
            processData: false,
            contentType: false,
            success: function(response){
                       $("#error").text("");
                       if(response==""){
                           $("#info").text("successfully added");
                           $('#myTable').append("<tr><td><input type='checkbox' name='cb' value='"+ response+"'><td>"+name + "</td><td>"+email + "</td><td>"+phone + "</td></tr>");
                           $("#addForm").hide();
                       }
                       else{
                           $("#info").text(response);
                       }
                  },
            error: function(){
                $("#info").text("");
                $("#error").text("Internal server error");
            },    
            statusCode: {
                        409: function(response,statusText) {
                            $("#info").text("");
                            $("#error").text("Name already exists ["+response.statusText+"]");
                        },
                        500: function(response,statusText) {
                            $("#info").text("");
                            $("#error").text("database problem ["+response.statusText+"]");
                        }
                      }
        });
        }
        </script>

    </head>
    <body bgcolor="FFFFCC">
        <center>
            <form:form action="" method="post" name="addForm" id="ufile" modelAttribute="upload" class="dark-matter">
                <h1>
                    Add Contacts <span>Please fill all the texts in the fields</span>
                </h1>
                <p>
                    <label> 
                        <input id="id" type="hidden">
                    </label> 
                    <label> 
                        <span>Your Name</span> 
                        <input id="name" type="text" name="name" placeholder="Your Full Name">
                    </label> 
                    <label> 
                        <span>Your Email</span> 
                        <input id="email" type="text" name="email" placeholder="Your Email">
                    </label> 
                    <label> 
                        <span>Your Phone</span> 
                        <input id="phone" type="text" name="phone" placeholder="Your phone">
                    </label>
                    <label>
                        <span>Upload Photo</span>
                        <input type="file" id="uploadfile" accept="image/*" name="uploadfile">              
                    </label>
                    <label> 
                        <span>&nbsp;</span> 
                        <input type="button" class="button"  id="btn" value="Add Me" onclick="doAdd()">
                    </label>
                </p>
            </form:form>
            <!--
            <div STYLE="color: #FF3333; background-color: #8888ff; width: 100px; border-radius: 10px; cursor: pointer;" id="sub">
                Add Me
            </div>
            -->
            <!--
            <input type="hidden" id="id" >
                <br/>
                Name : <input type="text" id="name"><br/><br/>
                Email : <input type="text" id="email"><br/><br/>
                Phone : <input type="text" id="phone"><br/><br/>
            <input type="button" value="Add Me" onclick="doAdd()">
            <br/>
            -->
        </center>
    </body>
</html>

在此处插入标题
函数doAdd(){
//获取表单值
var name=$('#name').val();
var email=$('#email').val();
var phone=$('#phone').val();
var file=document.getElementById(“上传文件”);
var formData=new formData();
formData.append(“上传”,file.files[0]);
append(“name”,$('#name').val();
formData.append(“email”,$(“#email”).val();
formData.append(“phone”,$(“#phone”).val();
$.ajax({
类型:“POST”,
url:“添加联系人”,
数据:formData,
processData:false,
contentType:false,
成功:功能(响应){
$(“#错误”).text(“”);
如果(响应==“”){
$(“#信息”).text(“已成功添加”);
$('#myTable')。追加(“+name+”“+email+”“+phone+”);
$(“#addForm”).hide();
}
否则{
$(“#信息”)。文本(回复);
}
},
错误:函数(){
$(“#信息”)。文本(“”);
$(“#错误”).text(“内部服务器错误”);
},    
状态代码:{
409:功能(响应、状态文本){
$(“#信息”)。文本(“”);
$(“#错误”).text(“名称已存在[“+response.statusText+”]);
},
500:功能(响应、状态文本){
$(“#信息”)。文本(“”);
$(“#错误”).text(“数据库问题[“+response.statusText+”]);
}
}
});
}
添加联系人请填写字段中的所有文本

你的名字
你的电子邮件
你的电话
上传照片


方法
MockMvcRequestBuilders.fileUpload

fileUpload@Deprecated public static
MockMultipartTtpServletRequestBuilder文件上载(java.net.URI)
不赞成。为了支持多部分(URI),创建一个
多部分请求的MockMultipartTTpServletRequestBuilder。
参数:uri-自以下日期起的URL:
4.0.3

要代替
fileUpload()
,请使用以下方法

  MockMultipartFile mockMultipartFile = new MockMultipartFile("user-file",fileName,
          "text/plain", "test data".getBytes());

  MockHttpServletRequestBuilder builder =
          MockMvcRequestBuilders.multipart("/upload")
                                .file(mockMultipartFile);


同样的问题和更好的答案:
fileUpload
现在被弃用了
fileUpload
已经被
org.springframework.test.web.servlet.request.MockMvcRequestBuilders#多部分(java.lang.String,java.lang.Object…)所取代
。如果出现错误
org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文件”不存在
,这是因为(和我一样)您没有充分遵循上述步骤。您必须使用
MockMultipartFile
,而不仅仅是所需文件的字节,
file()
的第一个参数必须是
“file”
,而不是文件名。如果
MissingServletRequestPartException
或在使用
transferTo
时出现
不支持操作异常
,则,另见:。