当前位置: 首页 > 知识库问答 >
问题:

使用Spring mvc和MockMVC上传文件

上官培
2023-03-14

我已成功将图像文件上载到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));
}

我的jsp文件如下所示:

<%@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>

共有2个答案

郎正初
2023-03-14

方法MockMvcRequestBuilders。不推荐使用文件上载

fileUpload@Deprecated public static
mockmultipartttpServletRequestBuilder fileUpload(java.net.URI URI)
已弃用。为了支持多部分(URI),为多部分请求创建一个
mockmultipartttpServletRequestBuilder
Parameters: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);

MockMultipartFile jsonFile = new MockMultipartFile("test.json", "", "application/json", "{\"key1\": \"value1\"}".getBytes());

mockMvc.perform(MockMvcRequestBuilders.multipart("/fileUpload")
                .file("file", jsonFile.getBytes())
                .characterEncoding("UTF-8"))
鲁才艺
2023-03-14
public void testAddContacts() throws Exception{
            File f = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
            System.out.println(f.isFile()+"  "+f.getName()+f.exists());
            FileInputStream fi1 = new FileInputStream(f);
            FileInputStream fi2 = new FileInputStream(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulips.jpg"));
            MockMultipartFile fstmp = new MockMultipartFile("upload", f.getName(), "multipart/form-data",fi1);
            MockMultipartFile secmp = new MockMultipartFile("upload", "Tulips.jpg","multipart/form-data",fi2); 
            MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
            mockMvc.perform(MockMvcRequestBuilders.fileUpload("/AddContacts")                
                    .file(fstmp)
                    .file(secmp)
                    .param("name","abc").param("email","abc@gmail.com").param("phone", "1234567890"))               
                    .andExpect(status().isOk());
    }
 类似资料:
  • 本文向大家介绍利用SpringMVC和Ajax实现文件上传功能,包括了利用SpringMVC和Ajax实现文件上传功能的使用技巧和注意事项,需要的朋友参考一下 个人根据相关资料实现利用SpringMVC和Ajax实现文件上传功能: 环境: 1.JDK1.7 2.maven3.3.9 3.Tomcat7 第一步: 导入相关jar包: 第二步: 配置springmvc-config.xml 第三步:

  • 本文向大家介绍SpringMVC 文件上传配置,多文件上传,使用的MultipartFile的实例,包括了SpringMVC 文件上传配置,多文件上传,使用的MultipartFile的实例的使用技巧和注意事项,需要的朋友参考一下 基本的SpringMVC的搭建在我的上一篇文章里已经写过了,这篇文章主要说明一下如何使用SpringMVC进行表单上的文件上传以及多个文件同时上传的步骤 文件上传项目的

  • 正在使用Spring MVC创建Restful Web服务... 下面是我的pom.xml: WEB-INF/web.xml: web-inf/mvc-dispatcher-servlet.xml: src/main/resources/database_db.xml: @Repository public class UserDAO{ } SRC/Test/Java: 这就像在print()语句

  • 本文向大家介绍springmvc+kindeditor文件上传实例详解,包括了springmvc+kindeditor文件上传实例详解的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了springmvc+kindeditor文件上传的具体代码,供大家参考,具体内容如下 下载kindeditor 压缩包里面的jar放到tomcat的lib文件夹下,kindeditor文件放工程里,不用的

  • 本文向大家介绍WebUploader+SpringMVC实现文件上传功能,包括了WebUploader+SpringMVC实现文件上传功能的使用技巧和注意事项,需要的朋友参考一下 WebUploader是由Baidu团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥html5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6

  • 本文向大家介绍SpringMVC + servlet3.0 文件上传的配置和实现代码,包括了SpringMVC + servlet3.0 文件上传的配置和实现代码的使用技巧和注意事项,需要的朋友参考一下 简单几步,实现SpringMVC+servlet3.0文件上传功能: 第一步:配置web.xml文件中的servlet,添加multipart-config: 第二步:在servlet.xml中配