android html 交互 安卓低版本 html5的formdata失效 20C

1.我的webview,设置了很多
WebSettings webSettings = allWebview.getSettings();
//设置可与js交互
webSettings.setJavaScriptEnabled(true);
// 把图片加载放在最后来加载渲染
webSettings.setBlockNetworkImage(true);

    //支持插件
    webSettings.setPluginState(WebSettings.PluginState.ON);
    //有无网络时的缓存
    if (JudgeNetwork.isNetworkConnected(context)) {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//没网,则从本地获取,即离线加载
    }

    // 可以读取文件缓存(manifest生效)
    webSettings.setAllowFileAccess(true);
    // 设置可以使用localStorage
    webSettings.setDomStorageEnabled(true);
    // 应用可以有数据库
    webSettings.setDatabaseEnabled(true);
    String dbPath = context.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    webSettings.setDatabasePath(dbPath);
    // 启用地理定位
    webSettings.setGeolocationEnabled(true);
    // 设置定位的数据库路径
    webSettings.setGeolocationDatabasePath(dbPath);
    // 设置编码格式
    webSettings.setDefaultTextEncodingName("utf-8");
    // 设置了这个,页面中就不会出现两边白边了
    allWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

// 支持跨域请求
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
webSettings.setAllowUniversalAccessFromFileURLs(true);
// 应用可以有缓存
webSettings.setAppCacheEnabled(true);
String appCaceDir = context.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
webSettings.setAppCachePath(appCaceDir);
// 默认使用缓存(前面进行了设置)
// webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
// 设置缓存最多可以有8M
webSettings.setAppCacheMaxSize(8 * 1024 * 1024);
allWebview.requestFocus();//触摸焦点起作用
allWebview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);//取消滚动条
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//设置允许js弹出alert对话框
// webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//允许混合内容,5.0之后的api
webSettings.setSaveFormData(true);
2.这个是html5的关键代码,其中alert(form.get("userId"));这个弹不出来,这个在7.0和6.0上面是弹出值的,但是在4.4.4和5.1上面则不能弹出值,也就是userId为空了
var form = new FormData(document.getElementById("patternForm"));
form.append("userId",userId);
alert(form.get("userId"));

2个回答

private class webViewClient extends WebChromeClient {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);
    }}
        当webview里的页面有alert时,会回调这个方法,你可以自己写一个原生的dailog弹出来

你可以自己写一个原生的会话

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
form表单 安卓机调用相机拍的照片用formdata上传,php中获取到的为空

## 安卓机调用相机拍的照片用formdata上传,php中获取到的为空 求助大神,万分感谢! (我这用的是TP框架) html: ![html:](https://img-ask.csdn.net/upload/201705/10/1494420802_866320.png) jq: ![jq:](https://img-ask.csdn.net/upload/201705/10/1494420847_913146.png) php: ![php:](https://img-ask.csdn.net/upload/201705/10/1494420869_77859.png)

客户端html5采用formdata提交信息,后台怎么接收信息并返回呢

后台用javaWeb来写,接收手机端formdata提交过来的信息,代码怎么接收并返回成功信息呢,谁写过类似的,提供个代码示例 html5用表单formdata来提交数据,使用ajax发送网络请求,提交到后台的数据格式是json的还是以对象形式过去的???

使用FormData上传图像获取在iOS上不起作用,但适用于Android / PC

<div class="post-text" itemprop="text"> <p>I've created an API for my React site to get/upload images using <code>fetch</code>. It's working for PC and Android phones, didn't bother to check Safari until the users said they cant do it on iPhones/iPads.</p> <p>Plugged in the macbook and saw i was getting CORS errors when uploading a file:</p> <pre><code>Origin https://xxxxxxx is not allowed by Access-Control-Allow-Origin </code></pre> <p>Funny thing is, when the page loads, it's calling the same API to retrieve existing images, and that works fine. My API is PHP, i've already added lines at the top:</p> <pre><code>header("Access-Control-Allow-Origin: https://xxxxxxx"); header("Access-Control-Allow-Methods: POST, OPTIONS"); header("Access-Control-Allow-Headers: X-Requested-With, Accept, Content-Type, Origin, Content-Length, Accept-Language, Host, User-Agent, Referer, Accept-Encoding, Connection"); </code></pre> <p>The infra guys swear they've opened up their WAF to allow uploads (i believe them because the PC/Android phones work)</p> <p>I've tried using Chrome on the iPhone but that doesn't work either.</p> <p>All the fetches run through this:</p> <pre><code> const API_URL = 'api_url'; const customFetcher = async (formData) =&gt; { let response = fetch(API_URL, { method: 'POST', body: formData, mode: 'cors' }) .then(r =&gt; { console.log('custom', r.status); if (r.status === 205) { throw new Error('Session expired'); } else { return r; } }); return response; } export default customFetcher; </code></pre> <p>The upload fetch that throws the CORS error:</p> <pre><code>let formData = new FormData(); formData.append('auth', this.props.user.state.token); formData.append('key', 'le_key') formData.append('what', 'upload'); formData.append('userId', this.props.user.state.userId); formData.append('serialNo', this.state.serialNo + '|' + this.state.firstName + '|' + this.state.lastName) formData.append('photo', this.state.selectedFiles[0]); customFetcher(formData) ... </code></pre> <p>The fetch to retrieve existing images:</p> <pre><code>let formData = new FormData(); formData.append('auth', this.props.user.state.token); formData.append('key', 'le_key') formData.append('what', 'photo'); formData.append('userId', this.props.user.state.userId); formData.append('serialNo', this.state.serialNo + '|' + this.state.firstName + '|' + this.state.lastName); customFetcher(formData) .then(r =&gt; { if (r.status !== 404) { return r.blob(); } else { this._setNoImage(); return false; } }) </code></pre> <p>PROGRESS: OK, found out it works if i take a fresh photo from the file input! Meaning its been sending an empty file which causes this error if i select from the file browser.</p> <p>So the question now is how am i able to grab that selected file? I do this:</p> <pre><code>&lt;FormControl type="file" onChange={this._updateFile} /&gt; _updateFile = (e) =&gt; { this.setState({ selectedFiles: e.target.files[0] }) } </code></pre> <p>I've even tried to check the file size but its good, somehow still sending nothing. Any ideas? TIA</p> </div>

如何让Ie9兼容 FormData

如何让Ie9兼容FormData 求解决方案                          

formdata java后台接受

前台用formdata传数据,后台怎么用java接收,前台使用js使用ajax传数据不是jquery

ajax使用formdata 提示错误

ajax使用formdata 提示Argument 1 of FormData.constructor is not an object 向后台传输一个表单对象 ``` $(document).ready(function () { var formData = new FormData("#form1"); formData.append('upLoad', $('input[type=file]')[0].files[0]); $.ajax({ url: "Handler3.ashx", type: "POST", data: formData, async: true, cache: false, processData: false, success: function () { }, error:function(){ } }); }) ```

执行$(#xxx).html(data)后, 表单失效

通过ajax执行的$(#xxx).html(data) 在data中有一个form 执行过后,form的submit就失效了

Formdata图片传输,java后台解析问题

这是前端代码: var formdata = new FormData(); formdata.append("files",files); var json = {"files":files}; $.ajax({ type: "post", url: "http://localhost:8080/Ajax1/practise", async: true, data: "files="+formdata, dataType: "text", success: function(data) { alert(data); }, error: function() { alert("登录出错"); } }); java后台要什么解析,通过 String fi = request.getParameter("files"); 输出是个对象 [object FormData] 要怎么解析formdata

Ajax不发送FormData

<div class="post-text" itemprop="text"> <p>I have several other identical functions working successfully but I can not get this last bit to work (The photo being 'uploaded' is not storing in the database). Any help at all would be much appreciated. <em>I understand the mysql statements are a deprecated version and will be changed.</em></p> <p><strong><em>Ajax function</em></strong></p> <pre><code>function uploadProLicense5() { var ajax = new XMLHttpRequest(); var dataFive = new FormData(); dataFive.append("professionalLicensePhotoFifthProivder", document.querySelector("#professionalLicensePhotoFifthProivder").files[0]); ajax.open("POST", "home.php"); ajax.onreadystatechange = function() { if (ajax.readyState === 4) { if (ajax.status === 200) { // OK $('#success_prolicense5').fadeIn().html("Photo Saved"); setTimeout(function(){ $('#success_prolicense5').fadeOut("Slow"); }, 2000); // here you can use the result (ajax.responseText) } else { // not OK alert('failed to upload photo, please try again'); } } }; ajax.send(dataFive); } </code></pre> <p><strong><em>Html</em></strong></p> <pre><code>&lt;div class="well col-lg-4 col-lg-offset-4 col-md-4 col-md-offset-4 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1" id="professionalphotoRow5"&gt; &lt;div class="text-center"&gt; &lt;label&gt;Upload professional license photo:&lt;/label&gt; &lt;/div&gt; &lt;div class="text-center"&gt; &lt;label id="label5thproviderPro"&gt;for 5th provider&lt;/label&gt; &lt;/div&gt; &lt;div class="col-sm-offset-4 col-xs-offset-4"&gt; &lt;input name="professionalLicensePhotoFifthProivder" id="professionalLicensePhotoFifthProivder" class="filestyle" data-input="false" type="file" accept="image/*"&gt; &lt;/div&gt; &lt;?php $savedTxt = "Photo Saved"; $notSavedTxt = "Photo Not Saved"; if (!empty($userRow[pro_license_photo_provider_five])) { echo "&lt;i class='glyphicon glyphicon-ok col-sm-offset-4 col-xs-offset-4' style='color: greenyellow;'&gt;" . "&lt;/i&gt; " . $savedTxt; } ?&gt; &lt;br&gt; &lt;div class="col-sm-offset-4 col-xs-offset-4"&gt; &lt;input id="saveProfessionalPhoto5" type="button" class="btn btn-default" name="saveProfessionalPhoto5" onclick="uploadProLicense5()" value="upload photo" style="background-color: #1d2b5c; color: white"/&gt; &lt;/div&gt; &lt;span id="success_prolicense5" class="text-success col-sm-offset-4 col-xs-offset-4"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p><strong><em>PHP</em></strong></p> <pre><code>$db_pro_license_img_provider_five = addslashes(file_get_contents($_FILES['professionalLicensePhotoFifthProivder']['tmp_name'])); $pro_image_data_provider_five = base64_encode($userRow[pro_license_photo_provider_five]); $pro_data_provider_five = substr($pro_image_data_provider_five, strpos($pro_image_data_provider_five, ",")); if(!empty($db_pro_license_img_provider_five)){ $sql = "UPDATE `wp_form` SET `pro_license_photo_provider_five`='$db_pro_license_img_provider_five' WHERE id =" . $_SESSION['user']; mysql_query($sql) or die(mysql_error()); $res = mysql_query("SELECT * FROM wp_form WHERE id=" . $_SESSION['user']); $userRow = mysql_fetch_array($res); } </code></pre> <p>Here's my network request</p> <p><a href="https://i.stack.imgur.com/A2jeQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A2jeQ.jpg" alt="enter image description here"></a></p> <p>And then my empty blob : (</p> <p><a href="https://i.stack.imgur.com/4ZpIE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4ZpIE.jpg" alt="enter image description here"></a></p> </div>

如何将带有Angular的FormData传递给Laravel操作方法

<div class="post-text" itemprop="text"> <p>I have an existing site built using Laravel. I am "duplicating" the action methods to use Angular, when I duplicated the action that posts a file I didn't get it to work. The $_FILES and $_POST global variables are not being set. </p> <p>Template: I have an input of type file, when a file is selected I want to send it to the server.</p> <pre><code>&lt;form enctype="multipart/form-data" [formGroup]="frmUploadFotoUm" (change)="onChange($event)"&gt; &lt;input type="file" [formControl]="frmUploadFotoUm.controls['fuUm']" /&gt; &lt;progress min="0" value="{{progressStatus}}" max="100"&gt;&lt;/progress&gt; &lt;/form&gt; </code></pre> <p>Handler:</p> <pre><code>onChange(event) : void { let fileList: FileList = event.target.files; let file: File = fileList[0]; let formData: FormData = new FormData(); formData.append('imagem', file); formData.append('imgNum', 1); formData.append('imgNome', "testandoAngular"); formData.append('tipoAnuncio', "venda"); formData.append('tipoImovel', "casa"); formData.append('imovelId', 361); formData.append('dirAnuncio', 8); this.http.post('http://www.example.com/apiuploadfotos/store', formData, {headers: new Headers({ 'Content-Type' : undefined})} ).subscribe(res =&gt; {}); } </code></pre> <p>The Laravel action method:</p> <p>Here I get "not working" all the time.</p> <pre><code> public function store(Request $request) { if($_FILES) { echo "working"; exit(); } else { echo "not working"; exit(); } } </code></pre> </div>

如何在 jQuery 中使用 ajax 请求发送 FormData 对象? [重复]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/5392344/sending-multipart-formdata-with-jquery-ajax" dir="ltr">Sending multipart/formdata with jQuery.ajax</a> <span class="question-originals-answer-count"> 12 answers </span> </li> </ul> </div> <p>The <a href="http://www.w3.org/TR/XMLHttpRequest2/" rel="noreferrer">XMLHttpRequest Level 2</a> standard (still a working draft) defines the <code>FormData</code> interface. This interface enables appending <code>File</code> objects to XHR-requests (Ajax-requests).</p> <p>Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used (read about that in <a href="https://stackoverflow.com/questions/6718664/is-it-possible-to-peform-an-asynchronous-cross-domain-file-upload/6963843">my other question</a>).</p> <p>This is how it works (example):</p> <pre><code>var xhr = new XMLHttpRequest(), fd = new FormData(); fd.append( 'file', input.files[0] ); xhr.open( 'POST', 'http://example.com/script.php', true ); xhr.onreadystatechange = handler; xhr.send( fd ); </code></pre> <p>where <code>input</code> is a <code>&lt;input type="file"&gt;</code> field, and <code>handler</code> is the success-handler for the Ajax-request.</p> <p>This works beautifully in all browsers (again, except IE).</p> <p>Now, I would like to make this functionality work with jQuery. I tried this:</p> <pre><code>var fd = new FormData(); fd.append( 'file', input.files[0] ); $.post( 'http://example.com/script.php', fd, handler ); </code></pre> <p>Unfortunately, that won't work (an "Illegal invocation" error is thrown - <a href="https://i.imgur.com/Uy8Xu.png" rel="noreferrer">screenshot is here</a>). I assume jQuery expects a simple key-value object representing form-field-names / values, and the <code>FormData</code> instance that I'm passing in is apparently incompatible.</p> <p>Now, since it is possible to pass a <code>FormData</code> instance into <code>xhr.send()</code>, I hope that it is also possible to make it work with jQuery.</p> <hr> <p><strong>Update:</strong></p> <p>I've created a "feature ticket" over at jQuery's Bug Tracker. It's here: <a href="http://bugs.jquery.com/ticket/9995" rel="noreferrer">http://bugs.jquery.com/ticket/9995</a></p> <p>I was suggested to use an "Ajax prefilter"...</p> <hr> <p><strong>Update:</strong></p> <p>First, let me give a demo demonstrating what behavior I would like to achieve. </p> <p>HTML:</p> <pre><code>&lt;form&gt; &lt;input type="file" id="file" name="file"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>JavaScript:</p> <pre><code>$( 'form' ).submit(function ( e ) { var data, xhr; data = new FormData(); data.append( 'file', $( '#file' )[0].files[0] ); xhr = new XMLHttpRequest(); xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true ); xhr.onreadystatechange = function ( response ) {}; xhr.send( data ); e.preventDefault(); }); </code></pre> <p>The above code results in this HTTP-request:</p> <p><img src="https://i.stack.imgur.com/YJYPm.png" alt="multipartformdata"></p> <p><strong>This is what I need</strong> - I want that "multipart/form-data" content-type!</p> <hr> <p>The proposed solution would be like so:</p> <pre><code>$( 'form' ).submit(function ( e ) { var data; data = new FormData(); data.append( 'file', $( '#file' )[0].files[0] ); $.ajax({ url: 'http://hacheck.tel.fer.hr/xml.pl', data: data, processData: false, type: 'POST', success: function ( data ) { alert( data ); } }); e.preventDefault(); }); </code></pre> <p>However, this results in:</p> <p><img src="https://i.stack.imgur.com/uU2Gi.png" alt="wrongcontenttype"></p> <p>As you can see, the content type is wrong...</p> </div> <p>转载于:https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery</p>

axios怎么同时传formdata和query值?

请求方式如下: ![图片说明](https://img-ask.csdn.net/upload/201905/05/1557043427_942787.jpg) 主要做的是一个申请退款的模块,要传字符串和图片。但是怎么同时发送字符串和formdata。用的是封装过的axios,实习狗在线求助,有没有研究生可以帮帮我 ![图片说明](https://img-ask.csdn.net/upload/201905/05/1557043448_249999.jpg)

FormData附加到$ _POST而不是$ _FILES?

<div class="post-text" itemprop="text"> <p>I'm trying to implement an upload routine for huge files, for this I'm chunking the file and send chunk by chunk to server so far so good.</p> <p>Now to identify the chunk-parts, I'm trying to send some more information than the pure filepart in <code>FormData</code>.</p> <pre><code>var xhr = new XMLHttpRequest(); xhr.open("POST", 'upload.php', true); var formData = new FormData(); formData.append("chunkpart", blob); // blob is Blob() or BlobBuilder formData.append("chunkNumber", sendCount); // sendCount is an integer formData.append("maxChunks", Math.ceil(maxChunks)); // maxChunks is a floatingpoint formData.append("fileID", fileID); // fileID is an almost unique string xhr.send(formData); </code></pre> <p>On the php side the <code>chunkpart</code> is found in <code>$_FILES</code> however <code>chunkNumber, maxChunks</code> and <code>fileID</code> are found in <code>$_POST</code>.</p> <p>My question here: Am I doing something wrong or did I just misunderstood how <code>FormData</code> works and how can I get it work like I expected?</p> </div>

FormData() - JQUERY

<div class="post-text" itemprop="text"> <p>Until i needed to upload a file throw AJAX, i never knew there was a method like "FormData()" that POST all values of the FORM and some more. </p> <p>I tested and worked perfect for file upload, but i could also send the other POST DATA, and this become even better. </p> <p>Can i always use this for all my forms throw AJAX even if i don't have a file to upload? Or there is a downsizing of doing this other the upload the file? </p> <p>In terms of performance, it's better to get the value of the input and send as data, or can i just use this to simplify?</p> <p>The only information i could find about this, was for file upload, and not general use of this method. </p> <p>Code Example:</p> <pre><code>&lt;form id="theForm"&gt; &lt;&lt;input id="test" type="text" name="test" placeholder="test" required=""&gt; &lt;input id="uploadFile" type="file" name="uploadFile" placeholder="uploadFile" required=""&gt; &lt;input id="submitFile" type="submit"&gt; &lt;/form&gt; $("#submitFile").on("click",function(event){ event.preventDefault(); var formData = new FormData($('#theForm')[0]); $.ajax({ type: "POST", url: "inc/upload.php", data: formData, contentType: false, processData: false, beforeSend: function() { //Do Something }, }) .done(function() { //Do Something }); }); </code></pre> <p>Thank you, Kind Regards!</p> </div>

获取formData后$ _POST为空

<div class="post-text" itemprop="text"> <p>when I try to fetch a formData with POST from JS to PHP, I obtain an empty $_POST array(), despite of Status Code is 200 OK. Can you help me?</p> <pre><code>function select_collection() { const tendina=document.querySelectorAll(".tendina"); for(all of tendina) { all.addEventListener('change', aggiungi); } } function aggiungi(event){ const tendina=event.target; const val=tendina.options[tendina.selectedIndex].value; const row_box= tendina.parentNode.parentNode; const child=row_box.childNodes; const url_image=child[0].childNodes[0].currentSrc; const id_google=child[1].childNodes[0].textContent.slice(11,); const titolo= child[1].childNodes[1].textContent.slice(8,); const autore= child[1].childNodes[2].textContent.slice(8,); const editore=child[1].childNodes[3].textContent.slice(9,); const pagine=child[1].childNodes[4].textContent.slice(8,); var formData = new FormData(); formData.append('titolo_racc', val); formData.append('id_google', id_google); formData.append('titolo', titolo); formData.append('autore', autore); formData.append('editore', editore); formData.append('pagine', pagine); fetch('http://localhost/progetto/inserisci_contenuto.php',{ method: "POST", body: formData }).then(onResponse).then(onText); </code></pre> <p>.tendina it's the class of a drop-down menù (select, option), title, author, publisher and pages refers to a book volume infos. I want to send this info to a PHP page.</p> <pre><code>$conn=new mysqli($servername, $username, $password, $dbname); if($conn-&gt;connect_error) { die ("Connection failed " .$conn-&gt;connect_error); } if(isset($_POST["titolo_racc"]) &amp;&amp; isset($_POST["id_google"] &amp;&amp; isset($_POST["titolo"] &amp;&amp; isset($_POST["autore"] &amp;&amp; isset($_POST["editore"] &amp;&amp; isset($_POST["pagine"])) { print_r($_POST); // array () print_r($_POST["titolo"]; //Undefined index: } </code></pre> </div>

通过XHR发送FormData后,$ _REQUEST始终为空

<div class="post-text" itemprop="text"> <p>I am trying to use the FormData object to send a series of fields, both file and non-file, to a PHP endpoint on my server. However, no matter what I've done, the <code>$_REQUEST</code> superglobal is always blank within the PHP endpoint. The code I'm using to send the FormData is below.</p> <pre><code>const formData = new FormData(); formData.append('token', this.props.token); formData.append('id', this.props.id); formData.append('name', this.props.name); formData.append('imageFile', this.props.image); formData.append('entryFile', this.props.file); formData.append('license', this.props.license); var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://path/to/endpoint', true); xhr.send(formData); </code></pre> </div>

安卓如何多选图片上传,目前使用的h5的input的 multiple这个属性,华为自带的浏览器不支持

想问问各位大佬还有没有什么其他的解决方案, 目前已知qq浏览器是支持的,但是生产环境规定只能用自带的浏览器, 想询问一下,如果不另外下载其他浏览器的话, 有什么方式可以解决华为浏览器不支持multiple属性无法多选图片上传的问题。

AJAX 提交 FormData 报data undefined

直接上代码js里的 $('#submit').click(function(){ var shop = {}; shop.shopName = $('#shop-name').val(); shop.shopAddr = $('#shop-addr').val(); shop.phone = $('#shop-phone').val(); shop.shopDesc = $('#shop-desc').val(); shop.shopCategory = { shopCategoryId:$('#shop-category').find('option').not(function(){ return !this.selected; }).data('id') }; shop.area = { areaId:$('#area').find('option').not(function(){ return !this.selected; }).data('id') }; var shopImg = $('#shop-img')[0].files[0]; var formData = new FormData(); formData.append('shopImg',shopImg); formData.append('shopStr',JSON.stringify(shop)); var verifyCodeActual = $('#j_captcha').val(); if(!verifyCodeActual){ $.toast('请输入验证码!'); return; } formData.append('verifyCodeActual',verifyCodeActual); alert(formData.get('shopStr')); $.ajax({ url:registerShopUrl, type:'POST', data: formData, contentType:false, processData:false, cache:false, success:function(data){ if(data.success){ $.toast('提交成功'); }else{ $.toast('提交失败' + data.errMsg); } $('#captcha_img').click(); } }); }); ![图片说明](https://img-ask.csdn.net/upload/201807/13/1531467788_432510.png)

使用FormData和PHP进行多个文件上传

<div class="post-text" itemprop="text"> <p>I'm running into an issue where I can choose multiple files fine from a form but when I check it in PHP, it only shows one file (but in the console in my browser, its showing two files) and it isn't moving the file(s) to the new location. I'm not really sure what is going on. </p> <p>Here is my code:</p> <p>jQuery:</p> <pre><code> $('#add-items-submit').on('click', function() { var store_name = $('#main-store-name').text(); var item_name = $('#add-item-name').val(); var item_price = $('#add-item-price').val(); var item_desc = $('#add-item-desc').val(); var item_num = $('#add-item-number').val(); var formData = new FormData(); formData.append('store_name', store_name); formData.append('item_name', item_name); formData.append('item_price', item_price); formData.append('item_desc', item_desc); formData.append('item_num', item_num); if (document.getElementById('add-item-image') == null) { document.getElementById('add-items-message').value = "Please add an image of the item if you wish to submit it"; } $.each($('#add-item-image')[0].files, function (i, file) { formData.append('item_file', file); }); $.ajax({ type: "POST", contentType: false, processData: false, url: '/user/add-items', dataType: "json", data: formData }).done(function (msg) { console.log(msg); $('#add-items-message').html(msg.success); }).fail(function (msg) { console.log(msg); $('#add-items-message').html(msg.failure); }); }); </code></pre> <p>PHP Code:</p> <pre><code> public function additemsAction() { $layout = $this-&gt;layout(); $layout-&gt;setTerminal(true); $view_model = new ViewModel(); $view_model-&gt;setTerminal(true); if ($this-&gt;getRequest()-&gt;isPost()) { try { $store_name = $this-&gt;params()-&gt;fromPost('store_name'); $item_name = $this-&gt;params()-&gt;fromPost('item_name'); $item_price = $this-&gt;params()-&gt;fromPost('item_price'); $item_desc = $this-&gt;params()-&gt;fromPost('item_desc'); $item_num = $this-&gt;params()-&gt;fromPost('item_num'); $item_image = $this-&gt;params()-&gt;fromFiles('item_file'); var_dump($item_image); if ($this-&gt;getUserService()-&gt;addItemsToStore($store_name, $item_name, $item_desc, $item_image, $item_num, $item_price)) { echo json_encode(array('success' =&gt; 'Item was successfully added to your store')); } } catch (\Exception $e) { echo json_encode(array('failure' =&gt; $e-&gt;getMessage())); } } return $view_model; } if (!is_dir(realpath(getcwd()) . '/public/images/uploads/store/' . $owner_id . '/' . $this-&gt;store_name . '/items')) { mkdir(realpath(getcwd()) . '/public/images/uploads/store/' . $owner_id . '/' . $this-&gt;store_name . '/items', 0777, true); } for ($i=0; $i&lt;count($item_image); $i++) { if (is_uploaded_file($item_image['tmp_name'][$i])) { move_uploaded_file($item_image['tmp_name'][$i], realpath(getcwd()) . '/public/images/uploads/store/' . $owner_id . '/' . $this-&gt;store_name . '/items/' . $item_image['name'][$i]); $this-&gt;imagick = new \Imagick(realpath(getcwd()) . '/public/images/uploads/store/' . $owner_id . '/' . $this-&gt;store_name . '/items/' . $item_image['name'][$i]); // automatically enhance them $this-&gt;imagick-&gt;enhanceImage(); $this-&gt;imagick-&gt;writeImagesFile(fopen(realpath(getcwd()) . '/public/images/uploads/store/' . $owner_id . '/' . $this-&gt;store_name . '/items/' . $item_image['name'][$i], 'wb')); } } </code></pre> <p>So, basically its not moving the files to the new location and as such executing imagick's functions on them, but I've checked my logs and no error was written in the apache logs, so I'm really confused. Oh, and I did use <code>var_dump</code> and the result was <code>"array(5) {↵ ["name"]=&gt;↵ string(40) "80E0C7D8-CEB1-49E5-839F-A08F0DE798CB.jpg"↵ ["type"]=&gt;↵ string(10) "image/jpeg"↵ ["tmp_name"]=&gt;↵ string(24) "C:\xampp\tmp\php89B6.tmp"↵ ["error"]=&gt;↵ int(0)↵ ["size"]=&gt;↵ int(68903)↵}</code></p> <p>So formData is getting all the files selected but PHP is only showing one, not multiple. </p> <p>Any help would be appreciated.</p> <p>Thanks.</p> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

外包程序员的幸福生活

今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大胆预测下未来5年的Web开发

在2019年的ReactiveConf 上,《Elm in Action》的作者Richard Feldman对未来5年Web开发的发展做了预测,很有意思,分享给大家。如果你有机会从头...

立即提问
相关内容推荐