hucheng91的专栏

个人github https://github.com/hucheng91/myBlog

利用FormData异步提交content-type为jpg,等流方面信息 --2016.04.20

利用FormData异步提交content-type为jpg,等流方面信息 –2016.04.20


平常在提交一个包含上传文件流信息都是使用form表单提交,最近在业务上需要异步提交图片,以前都是用一些js上传组键,这次没有用组键,最后找到了用FormData对像来提交信息。FormData的本质是将提交的东西伪装成了form表单,但是,是异步的

<div><input type="file" id="file_attachment"  name="file"/></div>
    $("#file_attachment").change(function(){
    var filedata = new FormData();
    var file = $("#file_attachment")[0].files[0];
    var nodeId = $("#node_page_nodeId_hidden").val();
    var ipa = {"categoryId":"SRVAPPR-00000009","productId":"","productName":"111111","engTuCode":"20160414103329737130","engTrCode":"2016041910454650560","engExecutorUc":"20160419104546663838","durationDay":"1","baseProduct":null};

        var url = "service_process_node_uploadAttachment.htm";
        if(nodeId){
            filedata.append("file",file);
            filedata.append("nodeId",nodeId);
            filedata.append("ipa",ipa);
            $.ajax({
                  url: url,
                  data: filedata,
                  processData: false,
                  contentType: false,
                  type: 'POST',
                  success: function(data){
                      var datajson = $.parseJSON(data);

                  }
                });
        }

    });

使用的方法

var filedata = new FormData(); 创建一个FormData()对象,然后用将需要的提交的内容用filedata.append()用键值对的模式添加到filedata里,在服务端接收就根据键来获取,值得注意的是,var file = $(“#file_attachment”)[0].files[0];
这里的files[0]只是单文件,当配置成 multiple,如

<input type="file" id="file_attachment" multiple tname="file"/>

获取这个多文件流就可以用var file = $(“#file_attachment”)[0],我当时获取这个file的时候花了不少时间,当时在网上看了半天,发现很多文章都是重复的介绍formData这个概念,demo也没有,有demo的也没有提怎么获取这个file对象,这个小坑得记下来;

看下发起这个ajax的时候htpp协议的头文件

Content-Disposition:attachment;filename=f.txt
Content-Type:text/html;charset=UTF-8
FM_CLIENT_ID:2016040811120556790
FM_SESSION_ID:aypvlhy3bbho1l6koku6vn8b
Server:Jetty(8.1.16.v20140903)
Transfer-Encoding:chunked
Request Headers
         Accept:*/*
        Accept-Encoding:gzip, deflate
        Accept-Language:zh-CN,zh;q=0.8,zh-TW;q=0.6
        Connection:keep-alive
        Content-Length:55623
        Content-Type:multipart/form-data;                         boundary=----WebKitFormBoundaryDu1rFGOOBCnSkQzj
        Cookie:JSESSIONID=aypvlhy3bbho1l6koku6vn8b
        Host:localhost:8080
        Origin:http://localhost:8080
        Referer:http://localhost:8080/farmen/partnerHome.htm
        User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64)         AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
        X-Requested-With:XMLHttpRequest
Query String Parameters
 (3)
Request Payload
------WebKitFormBoundaryDu1rFGOOBCnSkQzj
Content-Disposition: form-data; name="file"; filename="1.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryDu1rFGOOBCnSkQzj
Content-Disposition: form-data; name="nodeId"

0
------WebKitFormBoundaryZkq6BcqYyFLRBEk6
Content-Disposition: form-data; name="ipa"

{"categoryId":"SRVAPPR-00000009","productId":"","productName":"111111","engTuCode":"20160414103329737130 ","engTrCode":"2016041910454650560","engExecutorUc":"20160419104546663838","durationDay":"1","baseProduct":null}

------WebKitFormBoundaryDu1rFGOOBCnSkQzj--
Name
service_process_node_uploadAttachment.htm?&FM_CLIENT_ID=2016040811120556790&currentUserCode=20160415091813108347
1 requests ❘ 1.6KB transferred

看 Request Payload 可以看到其实还是form的提交,我理解是FormData将这个提交伪装成form表单提交
服务端是用java的SpringMvc框架写的,后台接受方法为

@RequestMapping("/service_process_node_uploadAttachment")
    @ResponseBody
public ResponseData<TmpTemplateForNodeVO> uploadAttachment(HttpServletRequest request,
            String nodeId,String ipa) {
            System.out.println(nodeId);
            System.out.println(ipa);
        List<DocumentBean> docBeanList = new ArrayList<DocumentBean>();
        try {
            docBeanList = handleFile(request);

        if (docBeanList.size() < 1) {
            result.setMessage("文件上传异常,请稍后再试");
            result.setSuccess(false);
            return result;
        }
        TmpTemplateForNodeVO vo = assemblyFileAndNode(docBeanList.get(0), actionId,nodeId);
        result.setSuccess(true);
        result.setEntity(vo);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public List<DocumentBean> handleFile(HttpServletRequest r)throws IOException{
         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(r.getSession().getServletContext());  
            if(multipartResolver.isMultipart(r)){  
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)r;  
                Iterator<String> iter = multiRequest.getFileNames();  
                List<DocumentBean> files = new ArrayList<DocumentBean>();
                while(iter.hasNext()){  
                    String para = iter.next();

                    MultipartFile file = multiRequest.getFile(para);  
                    if(file != null){  
                        if (file.getSize() > fileStore.getMaxFileSize()) {
                            logger.error("File Upload failed !  File Size can not More then "
                                    + fileStore.getMaxFileSize() / 1024 + " K");
                            continue;
                        }
                        DocumentBean doc = new DocumentBean();
                        String myFileName = file.getOriginalFilename();  
                        int index = myFileName.lastIndexOf(".");
                        String suffix = myFileName.substring(index + 1);
                        doc.setParameter(para);
                        doc.setFullname(myFileName);
                        doc.setSize(file.getSize());
                        doc.setSuffix(suffix);
                        doc.setFiletype(suffix.toUpperCase());
                        doc.setName(myFileName.substring(0,index-1));
                        try {
                            doc.setIo(file.getInputStream());
                            fileStore.saveFile(uInfo, doc);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        files.add(doc);
                    }  
                }  
                return files;
            }  
  • FormData也可以提交很复杂的数据类型,比较复杂的可以将他用字符串提交,然后在服务端将字符串解析成对象(java一般用阿里的fastJson包解析)

杂记:今天是同事小胖的生日,祝小胖生日快乐,大家一起吃了个饭,一起打了会桌球,听老大讲了很多,;

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/juncai91/article/details/52851618
文章标签: javascript 图片 表单
个人分类: javascript
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

利用FormData异步提交content-type为jpg,等流方面信息 --2016.04.20

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭