小编spi*_*der的帖子

使用Spring mvc和MockMVC上传文件

我已成功将图像文件上传到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 { …
Run Code Online (Sandbox Code Playgroud)

java spring mockmvc

11
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×1

mockmvc ×1

spring ×1