多图片上传 可预览增加删除,使用js局部刷新,并结合spingmvc使用

6 篇文章 0 订阅

1.使用XMLHttpRequest对象发送文件

js代码如下:

var form = new FormData();
        var xhr = new XMLHttpRequest();
        for (var i = 0, file; file = this.fileFilter[i]; i++) {
        	form.append("file", file); 
        }   
        xhr.open("POST", self.url, true);
        xhr.send(form);
使用springmvc的MultipartFile[] files参数接收不到文件,而直接表单提交是可以收到文件的,因此另谋出路,使用servlet进行接收。

2.servlet接收代码如下:

private String uploadPath;
    File tempPathFile;  
      
    protected void doPost(HttpServletRequest request,  
            HttpServletResponse response) throws ServletException, IOException {  
    	String fileName="";
    	String str="";
        try {  
            // Create a factory for disk-based file items  
        	
        	uploadPath=request.getSession().getServletContext()  
            .getRealPath("/") + "upload/" ;
            DiskFileItemFactory factory = new DiskFileItemFactory();  
  
            // Set factory constraints  
            factory.setSizeThreshold(4096);
            factory.setRepository(tempPathFile);
  
            // Create a new file upload handler  
            ServletFileUpload upload = new ServletFileUpload(factory);  
  
            // Set overall request size constraint  
            upload.setSizeMax(4194304);   
            List<FileItem> items = upload.parseRequest(request);         
            Iterator<FileItem> i = items.iterator();  
           
            while (i.hasNext()) {  
                FileItem fi = (FileItem) i.next();  
                 fileName = fi.getName();  
                if (fileName != null) {  
                    File fullFile = new File(new String(fi.getName().getBytes(), "utf-8")); 
                    File savedFile = new File(uploadPath, fullFile.getName()); 
                    if (!savedFile.getParentFile().exists())  
                    	savedFile.getParentFile().mkdirs();  
                    fi.write(savedFile);  
                    str=str+fullFile.getName()+"*";
                } 
                
            }  
           
          
        } catch (Exception e) {  
        	 System.out.print(e);
        }  
        
        response.getWriter().write("上传成功!"); 
     } 
3.servlet使用springmvc的注解需要加如下代码:

@Autowired 
    private TestDao testdao;
    public void init(ServletConfig config) throws ServletException {  
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,  
                config.getServletContext());  
    } 
4.整体效果图如下




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AICVer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值