图片上传

浅浅的花香味﹌ 2022-05-15 16:07 215阅读 0赞

1.页面表单

  1. <!--添加-->
  2. <div class="easyui-window" title="对商品进行添加或者修改" id="standardWindow" collapsible="false" minimizable="false" maximizable="false" modal="true" closed="true" style="width:600px;top:50px;left:200px">
  3. <div region="north" style="height:31px;overflow:hidden;" split="false" border="false">
  4. <div class="datagrid-toolbar">
  5. <a id="save" icon="icon-save" href="#" class="easyui-linkbutton" plain="true">保存</a>
  6. </div>
  7. </div>
  8. <div region="center" style="overflow:auto;padding:5px;" border="false">
  9. <form id="addstandardForm" enctype="multipart/form-data">
  10. <table class="table-edit" width="80%" align="center">
  11. <tr class="title">
  12. <td colspan="2">商品信息
  13. </td>
  14. </tr>
  15. <tr>
  16. <td>图片</td>
  17. <td>
  18. <input type="file" name="multipartFile" class="easyui-validatebox" data-options="required:true" />
  19. </td>
  20. </tr>
  21. <tr>
  22. <td>pname</td>
  23. <td>
  24. <input type="text" name="pname" class="easyui-validatebox" data-options="required:true" />
  25. </td>
  26. </tr>
  27. <tr>
  28. <td>price</td>
  29. <td>
  30. <input type="text" name="price" class="easyui-numberbox" required="true" />
  31. </td>
  32. </tr>
  33. </table>
  34. </form>
  35. </div>
  36. </div>

在这里插入图片描述

2.表单提交

  1. $("#save").bind("click",function () {
  2. var options={
  3. "url":"/product/addproduct",
  4. "type":"post",
  5. "statusCode":{
  6. 200: function () {
  7. $.messager.alert("提示", "添加成功");
  8. $("#standardWindow").window("close");
  9. $("#dg").datagrid("reload");
  10. },
  11. 500:function () {
  12. $.messager.alert("提示","服务器错误");
  13. }
  14. }
  15. };
  16. //提交表单
  17. $("#addstandardForm").ajaxSubmit(options);
  18. $.messager.alert("提示","提交成功");
  19. });

2.1.注意

在这里插入图片描述
在这里插入图片描述

2.1.1 jquery.form.js

  1. /*! * jQuery Form Plugin * version: 3.51.0-2014.06.20 * Requires jQuery v1.5 or later * Copyright (c) 2014 M. Alsup * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses. * https://github.com/malsup/form#copyright-and-license */
  2. /*global ActiveXObject */
  3. // AMD support
  4. (function (factory) {
  5. "use strict";
  6. if (typeof define === 'function' && define.amd) {
  7. // using AMD; register as anon module
  8. define(['jquery'], factory);
  9. } else {
  10. // no AMD; invoke directly
  11. factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );
  12. }
  13. }
  14. (function($) {
  15. "use strict";
  16. /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */
  17. /** * Feature detection */
  18. var feature = { };
  19. feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
  20. feature.formdata = window.FormData !== undefined;
  21. var hasProp = !!$.fn.prop;
  22. // attr2 uses prop when it can but checks the return type for
  23. // an expected string. this accounts for the case where a form
  24. // contains inputs with names like "action" or "method"; in those
  25. // cases "prop" returns the element
  26. $.fn.attr2 = function() {
  27. if ( ! hasProp ) {
  28. return this.attr.apply(this, arguments);
  29. }
  30. var val = this.prop.apply(this, arguments);
  31. if ( ( val && val.jquery ) || typeof val === 'string' ) {
  32. return val;
  33. }
  34. return this.attr.apply(this, arguments);
  35. };
  36. /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */
  37. $.fn.ajaxSubmit = function(options) {
  38. /*jshint scripturl:true */
  39. // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
  40. if (!this.length) {
  41. log('ajaxSubmit: skipping submit process - no element selected');
  42. return this;
  43. }
  44. var method, action, url, $form = this;
  45. if (typeof options == 'function') {
  46. options = { success: options };
  47. }
  48. else if ( options === undefined ) {
  49. options = { };
  50. }
  51. method = options.type || this.attr2('method');
  52. action = options.url || this.attr2('action');
  53. url = (typeof action === 'string') ? $.trim(action) : '';
  54. url = url || window.location.href || '';
  55. if (url) {
  56. // clean url (don't include hash vaue)
  57. url = (url.match(/^([^#]+)/)||[])[1];
  58. }
  59. options = $.extend(true, {
  60. url: url,
  61. success: $.ajaxSettings.success,
  62. type: method || $.ajaxSettings.type,
  63. iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
  64. }, options);
  65. // hook for manipulating the form data before it is extracted;
  66. // convenient for use with rich editors like tinyMCE or FCKEditor
  67. var veto = { };
  68. this.trigger('form-pre-serialize', [this, options, veto]);
  69. if (veto.veto) {
  70. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  71. return this;
  72. }
  73. // provide opportunity to alter form data before it is serialized
  74. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  75. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  76. return this;
  77. }
  78. var traditional = options.traditional;
  79. if ( traditional === undefined ) {
  80. traditional = $.ajaxSettings.traditional;
  81. }
  82. var elements = [];
  83. var qx, a = this.formToArray(options.semantic, elements);
  84. if (options.data) {
  85. options.extraData = options.data;
  86. qx = $.param(options.data, traditional);
  87. }
  88. // give pre-submit callback an opportunity to abort the submit
  89. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  90. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  91. return this;
  92. }
  93. // fire vetoable 'validate' event
  94. this.trigger('form-submit-validate', [a, this, options, veto]);
  95. if (veto.veto) {
  96. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  97. return this;
  98. }
  99. var q = $.param(a, traditional);
  100. if (qx) {
  101. q = ( q ? (q + '&' + qx) : qx );
  102. }
  103. if (options.type.toUpperCase() == 'GET') {
  104. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  105. options.data = null; // data is null for 'get'
  106. }
  107. else {
  108. options.data = q; // data is the query string for 'post'
  109. }
  110. var callbacks = [];
  111. if (options.resetForm) {
  112. callbacks.push(function() { $form.resetForm(); });
  113. }
  114. if (options.clearForm) {
  115. callbacks.push(function() { $form.clearForm(options.includeHidden); });
  116. }
  117. // perform a load on the target only if dataType is not provided
  118. if (!options.dataType && options.target) {
  119. var oldSuccess = options.success || function(){ };
  120. callbacks.push(function(data) {
  121. var fn = options.replaceTarget ? 'replaceWith' : 'html';
  122. $(options.target)[fn](data).each(oldSuccess, arguments);
  123. });
  124. }
  125. else if (options.success) {
  126. callbacks.push(options.success);
  127. }
  128. options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
  129. var context = options.context || this ; // jQuery 1.4+ supports scope context
  130. for (var i=0, max=callbacks.length; i < max; i++) {
  131. callbacks[i].apply(context, [data, status, xhr || $form, $form]);
  132. }
  133. };
  134. if (options.error) {
  135. var oldError = options.error;
  136. options.error = function(xhr, status, error) {
  137. var context = options.context || this;
  138. oldError.apply(context, [xhr, status, error, $form]);
  139. };
  140. }
  141. if (options.complete) {
  142. var oldComplete = options.complete;
  143. options.complete = function(xhr, status) {
  144. var context = options.context || this;
  145. oldComplete.apply(context, [xhr, status, $form]);
  146. };
  147. }
  148. // are there files to upload?
  149. // [value] (issue #113), also see comment:
  150. // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
  151. var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; });
  152. var hasFileInputs = fileInputs.length > 0;
  153. var mp = 'multipart/form-data';
  154. var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
  155. var fileAPI = feature.fileapi && feature.formdata;
  156. log("fileAPI :" + fileAPI);
  157. var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
  158. var jqxhr;
  159. // options.iframe allows user to force iframe mode
  160. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  161. if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
  162. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  163. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  164. if (options.closeKeepAlive) {
  165. $.get(options.closeKeepAlive, function() {
  166. jqxhr = fileUploadIframe(a);
  167. });
  168. }
  169. else {
  170. jqxhr = fileUploadIframe(a);
  171. }
  172. }
  173. else if ((hasFileInputs || multipart) && fileAPI) {
  174. jqxhr = fileUploadXhr(a);
  175. }
  176. else {
  177. jqxhr = $.ajax(options);
  178. }
  179. $form.removeData('jqxhr').data('jqxhr', jqxhr);
  180. // clear element array
  181. for (var k=0; k < elements.length; k++) {
  182. elements[k] = null;
  183. }
  184. // fire 'notify' event
  185. this.trigger('form-submit-notify', [this, options]);
  186. return this;
  187. // utility fn for deep serialization
  188. function deepSerialize(extraData){
  189. var serialized = $.param(extraData, options.traditional).split('&');
  190. var len = serialized.length;
  191. var result = [];
  192. var i, part;
  193. for (i=0; i < len; i++) {
  194. // #252; undo param space replacement
  195. serialized[i] = serialized[i].replace(/\+/g,' ');
  196. part = serialized[i].split('=');
  197. // #278; use array instead of object storage, favoring array serializations
  198. result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
  199. }
  200. return result;
  201. }
  202. // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
  203. function fileUploadXhr(a) {
  204. var formdata = new FormData();
  205. for (var i=0; i < a.length; i++) {
  206. formdata.append(a[i].name, a[i].value);
  207. }
  208. if (options.extraData) {
  209. var serializedData = deepSerialize(options.extraData);
  210. for (i=0; i < serializedData.length; i++) {
  211. if (serializedData[i]) {
  212. formdata.append(serializedData[i][0], serializedData[i][1]);
  213. }
  214. }
  215. }
  216. options.data = null;
  217. var s = $.extend(true, { }, $.ajaxSettings, options, {
  218. contentType: false,
  219. processData: false,
  220. cache: false,
  221. type: method || 'POST'
  222. });
  223. if (options.uploadProgress) {
  224. // workaround because jqXHR does not expose upload property
  225. s.xhr = function() {
  226. var xhr = $.ajaxSettings.xhr();
  227. if (xhr.upload) {
  228. xhr.upload.addEventListener('progress', function(event) {
  229. var percent = 0;
  230. var position = event.loaded || event.position; /*event.position is deprecated*/
  231. var total = event.total;
  232. if (event.lengthComputable) {
  233. percent = Math.ceil(position / total * 100);
  234. }
  235. options.uploadProgress(event, position, total, percent);
  236. }, false);
  237. }
  238. return xhr;
  239. };
  240. }
  241. s.data = null;
  242. var beforeSend = s.beforeSend;
  243. s.beforeSend = function(xhr, o) {
  244. //Send FormData() provided by user
  245. if (options.formData) {
  246. o.data = options.formData;
  247. }
  248. else {
  249. o.data = formdata;
  250. }
  251. if(beforeSend) {
  252. beforeSend.call(this, xhr, o);
  253. }
  254. };
  255. return $.ajax(s);
  256. }
  257. // private function for handling file uploads (hat tip to YAHOO!)
  258. function fileUploadIframe(a) {
  259. var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
  260. var deferred = $.Deferred();
  261. // #341
  262. deferred.abort = function(status) {
  263. xhr.abort(status);
  264. };
  265. if (a) {
  266. // ensure that every serialized input is still enabled
  267. for (i=0; i < elements.length; i++) {
  268. el = $(elements[i]);
  269. if ( hasProp ) {
  270. el.prop('disabled', false);
  271. }
  272. else {
  273. el.removeAttr('disabled');
  274. }
  275. }
  276. }
  277. s = $.extend(true, { }, $.ajaxSettings, options);
  278. s.context = s.context || s;
  279. id = 'jqFormIO' + (new Date().getTime());
  280. if (s.iframeTarget) {
  281. $io = $(s.iframeTarget);
  282. n = $io.attr2('name');
  283. if (!n) {
  284. $io.attr2('name', id);
  285. }
  286. else {
  287. id = n;
  288. }
  289. }
  290. else {
  291. $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
  292. $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
  293. }
  294. io = $io[0];
  295. xhr = { // mock object
  296. aborted: 0,
  297. responseText: null,
  298. responseXML: null,
  299. status: 0,
  300. statusText: 'n/a',
  301. getAllResponseHeaders: function() { },
  302. getResponseHeader: function() { },
  303. setRequestHeader: function() { },
  304. abort: function(status) {
  305. var e = (status === 'timeout' ? 'timeout' : 'aborted');
  306. log('aborting upload... ' + e);
  307. this.aborted = 1;
  308. try { // #214, #257
  309. if (io.contentWindow.document.execCommand) {
  310. io.contentWindow.document.execCommand('Stop');
  311. }
  312. }
  313. catch(ignore) { }
  314. $io.attr('src', s.iframeSrc); // abort op in progress
  315. xhr.error = e;
  316. if (s.error) {
  317. s.error.call(s.context, xhr, e, status);
  318. }
  319. if (g) {
  320. $.event.trigger("ajaxError", [xhr, s, e]);
  321. }
  322. if (s.complete) {
  323. s.complete.call(s.context, xhr, e);
  324. }
  325. }
  326. };
  327. g = s.global;
  328. // trigger ajax global events so that activity/block indicators work like normal
  329. if (g && 0 === $.active++) {
  330. $.event.trigger("ajaxStart");
  331. }
  332. if (g) {
  333. $.event.trigger("ajaxSend", [xhr, s]);
  334. }
  335. if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
  336. if (s.global) {
  337. $.active--;
  338. }
  339. deferred.reject();
  340. return deferred;
  341. }
  342. if (xhr.aborted) {
  343. deferred.reject();
  344. return deferred;
  345. }
  346. // add submitting element to data if we know it
  347. sub = form.clk;
  348. if (sub) {
  349. n = sub.name;
  350. if (n && !sub.disabled) {
  351. s.extraData = s.extraData || { };
  352. s.extraData[n] = sub.value;
  353. if (sub.type == "image") {
  354. s.extraData[n+'.x'] = form.clk_x;
  355. s.extraData[n+'.y'] = form.clk_y;
  356. }
  357. }
  358. }
  359. var CLIENT_TIMEOUT_ABORT = 1;
  360. var SERVER_ABORT = 2;
  361. function getDoc(frame) {
  362. /* it looks like contentWindow or contentDocument do not * carry the protocol property in ie8, when running under ssl * frame.document is the only valid response document, since * the protocol is know but not on the other two objects. strange? * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy */
  363. var doc = null;
  364. // IE8 cascading access check
  365. try {
  366. if (frame.contentWindow) {
  367. doc = frame.contentWindow.document;
  368. }
  369. } catch(err) {
  370. // IE8 access denied under ssl & missing protocol
  371. log('cannot get iframe.contentWindow document: ' + err);
  372. }
  373. if (doc) { // successful getting content
  374. return doc;
  375. }
  376. try { // simply checking may throw in ie8 under ssl or mismatched protocol
  377. doc = frame.contentDocument ? frame.contentDocument : frame.document;
  378. } catch(err) {
  379. // last attempt
  380. log('cannot get iframe.contentDocument: ' + err);
  381. doc = frame.document;
  382. }
  383. return doc;
  384. }
  385. // Rails CSRF hack (thanks to Yvan Barthelemy)
  386. var csrf_token = $('meta[name=csrf-token]').attr('content');
  387. var csrf_param = $('meta[name=csrf-param]').attr('content');
  388. if (csrf_param && csrf_token) {
  389. s.extraData = s.extraData || { };
  390. s.extraData[csrf_param] = csrf_token;
  391. }
  392. // take a breath so that pending repaints get some cpu time before the upload starts
  393. function doSubmit() {
  394. // make sure form attrs are set
  395. var t = $form.attr2('target'),
  396. a = $form.attr2('action'),
  397. mp = 'multipart/form-data',
  398. et = $form.attr('enctype') || $form.attr('encoding') || mp;
  399. // update form attrs in IE friendly way
  400. form.setAttribute('target',id);
  401. if (!method || /post/i.test(method) ) {
  402. form.setAttribute('method', 'POST');
  403. }
  404. if (a != s.url) {
  405. form.setAttribute('action', s.url);
  406. }
  407. // ie borks in some cases when setting encoding
  408. if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
  409. $form.attr({
  410. encoding: 'multipart/form-data',
  411. enctype: 'multipart/form-data'
  412. });
  413. }
  414. // support timout
  415. if (s.timeout) {
  416. timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
  417. }
  418. // look for server aborts
  419. function checkState() {
  420. try {
  421. var state = getDoc(io).readyState;
  422. log('state = ' + state);
  423. if (state && state.toLowerCase() == 'uninitialized') {
  424. setTimeout(checkState,50);
  425. }
  426. }
  427. catch(e) {
  428. log('Server abort: ' , e, ' (', e.name, ')');
  429. cb(SERVER_ABORT);
  430. if (timeoutHandle) {
  431. clearTimeout(timeoutHandle);
  432. }
  433. timeoutHandle = undefined;
  434. }
  435. }
  436. // add "extra" data to form if provided in options
  437. var extraInputs = [];
  438. try {
  439. if (s.extraData) {
  440. for (var n in s.extraData) {
  441. if (s.extraData.hasOwnProperty(n)) {
  442. // if using the $.param format that allows for multiple values with the same name
  443. if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
  444. extraInputs.push(
  445. $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
  446. .appendTo(form)[0]);
  447. } else {
  448. extraInputs.push(
  449. $('<input type="hidden" name="'+n+'">').val(s.extraData[n])
  450. .appendTo(form)[0]);
  451. }
  452. }
  453. }
  454. }
  455. if (!s.iframeTarget) {
  456. // add iframe to doc and submit the form
  457. $io.appendTo('body');
  458. }
  459. if (io.attachEvent) {
  460. io.attachEvent('onload', cb);
  461. }
  462. else {
  463. io.addEventListener('load', cb, false);
  464. }
  465. setTimeout(checkState,15);
  466. try {
  467. form.submit();
  468. } catch(err) {
  469. // just in case form has element with name/id of 'submit'
  470. var submitFn = document.createElement('form').submit;
  471. submitFn.apply(form);
  472. }
  473. }
  474. finally {
  475. // reset attrs and remove "extra" input elements
  476. form.setAttribute('action',a);
  477. form.setAttribute('enctype', et); // #380
  478. if(t) {
  479. form.setAttribute('target', t);
  480. } else {
  481. $form.removeAttr('target');
  482. }
  483. $(extraInputs).remove();
  484. }
  485. }
  486. if (s.forceSync) {
  487. doSubmit();
  488. }
  489. else {
  490. setTimeout(doSubmit, 10); // this lets dom updates render
  491. }
  492. var data, doc, domCheckCount = 50, callbackProcessed;
  493. function cb(e) {
  494. if (xhr.aborted || callbackProcessed) {
  495. return;
  496. }
  497. doc = getDoc(io);
  498. if(!doc) {
  499. log('cannot access response document');
  500. e = SERVER_ABORT;
  501. }
  502. if (e === CLIENT_TIMEOUT_ABORT && xhr) {
  503. xhr.abort('timeout');
  504. deferred.reject(xhr, 'timeout');
  505. return;
  506. }
  507. else if (e == SERVER_ABORT && xhr) {
  508. xhr.abort('server abort');
  509. deferred.reject(xhr, 'error', 'server abort');
  510. return;
  511. }
  512. if (!doc || doc.location.href == s.iframeSrc) {
  513. // response not received yet
  514. if (!timedOut) {
  515. return;
  516. }
  517. }
  518. if (io.detachEvent) {
  519. io.detachEvent('onload', cb);
  520. }
  521. else {
  522. io.removeEventListener('load', cb, false);
  523. }
  524. var status = 'success', errMsg;
  525. try {
  526. if (timedOut) {
  527. throw 'timeout';
  528. }
  529. var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  530. log('isXml='+isXml);
  531. if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
  532. if (--domCheckCount) {
  533. // in some browsers (Opera) the iframe DOM is not always traversable when
  534. // the onload callback fires, so we loop a bit to accommodate
  535. log('requeing onLoad callback, DOM not available');
  536. setTimeout(cb, 250);
  537. return;
  538. }
  539. // let this fall through because server response could be an empty document
  540. //log('Could not access iframe DOM after mutiple tries.');
  541. //throw 'DOMException: not available';
  542. }
  543. //log('response detected');
  544. var docRoot = doc.body ? doc.body : doc.documentElement;
  545. xhr.responseText = docRoot ? docRoot.innerHTML : null;
  546. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  547. if (isXml) {
  548. s.dataType = 'xml';
  549. }
  550. xhr.getResponseHeader = function(header){
  551. var headers = { 'content-type': s.dataType};
  552. return headers[header.toLowerCase()];
  553. };
  554. // support for XHR 'status' & 'statusText' emulation :
  555. if (docRoot) {
  556. xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
  557. xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
  558. }
  559. var dt = (s.dataType || '').toLowerCase();
  560. var scr = /(json|script|text)/.test(dt);
  561. if (scr || s.textarea) {
  562. // see if user embedded response in textarea
  563. var ta = doc.getElementsByTagName('textarea')[0];
  564. if (ta) {
  565. xhr.responseText = ta.value;
  566. // support for XHR 'status' & 'statusText' emulation :
  567. xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
  568. xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
  569. }
  570. else if (scr) {
  571. // account for browsers injecting pre around json response
  572. var pre = doc.getElementsByTagName('pre')[0];
  573. var b = doc.getElementsByTagName('body')[0];
  574. if (pre) {
  575. xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
  576. }
  577. else if (b) {
  578. xhr.responseText = b.textContent ? b.textContent : b.innerText;
  579. }
  580. }
  581. }
  582. else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
  583. xhr.responseXML = toXml(xhr.responseText);
  584. }
  585. try {
  586. data = httpData(xhr, dt, s);
  587. }
  588. catch (err) {
  589. status = 'parsererror';
  590. xhr.error = errMsg = (err || status);
  591. }
  592. }
  593. catch (err) {
  594. log('error caught: ',err);
  595. status = 'error';
  596. xhr.error = errMsg = (err || status);
  597. }
  598. if (xhr.aborted) {
  599. log('upload aborted');
  600. status = null;
  601. }
  602. if (xhr.status) { // we've set xhr.status
  603. status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
  604. }
  605. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  606. if (status === 'success') {
  607. if (s.success) {
  608. s.success.call(s.context, data, 'success', xhr);
  609. }
  610. deferred.resolve(xhr.responseText, 'success', xhr);
  611. if (g) {
  612. $.event.trigger("ajaxSuccess", [xhr, s]);
  613. }
  614. }
  615. else if (status) {
  616. if (errMsg === undefined) {
  617. errMsg = xhr.statusText;
  618. }
  619. if (s.error) {
  620. s.error.call(s.context, xhr, status, errMsg);
  621. }
  622. deferred.reject(xhr, 'error', errMsg);
  623. if (g) {
  624. $.event.trigger("ajaxError", [xhr, s, errMsg]);
  625. }
  626. }
  627. if (g) {
  628. $.event.trigger("ajaxComplete", [xhr, s]);
  629. }
  630. if (g && ! --$.active) {
  631. $.event.trigger("ajaxStop");
  632. }
  633. if (s.complete) {
  634. s.complete.call(s.context, xhr, status);
  635. }
  636. callbackProcessed = true;
  637. if (s.timeout) {
  638. clearTimeout(timeoutHandle);
  639. }
  640. // clean up
  641. setTimeout(function() {
  642. if (!s.iframeTarget) {
  643. $io.remove();
  644. }
  645. else { //adding else to clean up existing iframe response.
  646. $io.attr('src', s.iframeSrc);
  647. }
  648. xhr.responseXML = null;
  649. }, 100);
  650. }
  651. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  652. if (window.ActiveXObject) {
  653. doc = new ActiveXObject('Microsoft.XMLDOM');
  654. doc.async = 'false';
  655. doc.loadXML(s);
  656. }
  657. else {
  658. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  659. }
  660. return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
  661. };
  662. var parseJSON = $.parseJSON || function(s) {
  663. /*jslint evil:true */
  664. return window['eval']('(' + s + ')');
  665. };
  666. var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
  667. var ct = xhr.getResponseHeader('content-type') || '',
  668. xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
  669. data = xml ? xhr.responseXML : xhr.responseText;
  670. if (xml && data.documentElement.nodeName === 'parsererror') {
  671. if ($.error) {
  672. $.error('parsererror');
  673. }
  674. }
  675. if (s && s.dataFilter) {
  676. data = s.dataFilter(data, type);
  677. }
  678. if (typeof data === 'string') {
  679. if (type === 'json' || !type && ct.indexOf('json') >= 0) {
  680. data = parseJSON(data);
  681. } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
  682. $.globalEval(data);
  683. }
  684. }
  685. return data;
  686. };
  687. return deferred;
  688. }
  689. };
  690. /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */
  691. $.fn.ajaxForm = function(options) {
  692. options = options || { };
  693. options.delegation = options.delegation && $.isFunction($.fn.on);
  694. // in jQuery 1.3+ we can fix mistakes with the ready state
  695. if (!options.delegation && this.length === 0) {
  696. var o = { s: this.selector, c: this.context };
  697. if (!$.isReady && o.s) {
  698. log('DOM not ready, queuing ajaxForm');
  699. $(function() {
  700. $(o.s,o.c).ajaxForm(options);
  701. });
  702. return this;
  703. }
  704. // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  705. log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
  706. return this;
  707. }
  708. if ( options.delegation ) {
  709. $(document)
  710. .off('submit.form-plugin', this.selector, doAjaxSubmit)
  711. .off('click.form-plugin', this.selector, captureSubmittingElement)
  712. .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
  713. .on('click.form-plugin', this.selector, options, captureSubmittingElement);
  714. return this;
  715. }
  716. return this.ajaxFormUnbind()
  717. .bind('submit.form-plugin', options, doAjaxSubmit)
  718. .bind('click.form-plugin', options, captureSubmittingElement);
  719. };
  720. // private event handlers
  721. function doAjaxSubmit(e) {
  722. /*jshint validthis:true */
  723. var options = e.data;
  724. if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
  725. e.preventDefault();
  726. $(e.target).ajaxSubmit(options); // #365
  727. }
  728. }
  729. function captureSubmittingElement(e) {
  730. /*jshint validthis:true */
  731. var target = e.target;
  732. var $el = $(target);
  733. if (!($el.is("[type=submit],[type=image]"))) {
  734. // is this a child element of the submit el? (ex: a span within a button)
  735. var t = $el.closest('[type=submit]');
  736. if (t.length === 0) {
  737. return;
  738. }
  739. target = t[0];
  740. }
  741. var form = this;
  742. form.clk = target;
  743. if (target.type == 'image') {
  744. if (e.offsetX !== undefined) {
  745. form.clk_x = e.offsetX;
  746. form.clk_y = e.offsetY;
  747. } else if (typeof $.fn.offset == 'function') {
  748. var offset = $el.offset();
  749. form.clk_x = e.pageX - offset.left;
  750. form.clk_y = e.pageY - offset.top;
  751. } else {
  752. form.clk_x = e.pageX - target.offsetLeft;
  753. form.clk_y = e.pageY - target.offsetTop;
  754. }
  755. }
  756. // clear form vars
  757. setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
  758. }
  759. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  760. $.fn.ajaxFormUnbind = function() {
  761. return this.unbind('submit.form-plugin click.form-plugin');
  762. };
  763. /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */
  764. $.fn.formToArray = function(semantic, elements) {
  765. var a = [];
  766. if (this.length === 0) {
  767. return a;
  768. }
  769. var form = this[0];
  770. var formId = this.attr('id');
  771. var els = semantic ? form.getElementsByTagName('*') : form.elements;
  772. var els2;
  773. if (els && !/MSIE [678]/.test(navigator.userAgent)) { // #390
  774. els = $(els).get(); // convert to standard array
  775. }
  776. // #386; account for inputs outside the form which use the 'form' attribute
  777. if ( formId ) {
  778. els2 = $(':input[form="' + formId + '"]').get(); // hat tip @thet
  779. if ( els2.length ) {
  780. els = (els || []).concat(els2);
  781. }
  782. }
  783. if (!els || !els.length) {
  784. return a;
  785. }
  786. var i,j,n,v,el,max,jmax;
  787. for(i=0, max=els.length; i < max; i++) {
  788. el = els[i];
  789. n = el.name;
  790. if (!n || el.disabled) {
  791. continue;
  792. }
  793. if (semantic && form.clk && el.type == "image") {
  794. // handle image inputs on the fly when semantic == true
  795. if(form.clk == el) {
  796. a.push({ name: n, value: $(el).val(), type: el.type });
  797. a.push({ name: n+'.x', value: form.clk_x}, { name: n+'.y', value: form.clk_y});
  798. }
  799. continue;
  800. }
  801. v = $.fieldValue(el, true);
  802. if (v && v.constructor == Array) {
  803. if (elements) {
  804. elements.push(el);
  805. }
  806. for(j=0, jmax=v.length; j < jmax; j++) {
  807. a.push({ name: n, value: v[j]});
  808. }
  809. }
  810. else if (feature.fileapi && el.type == 'file') {
  811. if (elements) {
  812. elements.push(el);
  813. }
  814. var files = el.files;
  815. if (files.length) {
  816. for (j=0; j < files.length; j++) {
  817. a.push({ name: n, value: files[j], type: el.type});
  818. }
  819. }
  820. else {
  821. // #180
  822. a.push({ name: n, value: '', type: el.type });
  823. }
  824. }
  825. else if (v !== null && typeof v != 'undefined') {
  826. if (elements) {
  827. elements.push(el);
  828. }
  829. a.push({ name: n, value: v, type: el.type, required: el.required});
  830. }
  831. }
  832. if (!semantic && form.clk) {
  833. // input type=='image' are not found in elements array! handle it here
  834. var $input = $(form.clk), input = $input[0];
  835. n = input.name;
  836. if (n && !input.disabled && input.type == 'image') {
  837. a.push({ name: n, value: $input.val()});
  838. a.push({ name: n+'.x', value: form.clk_x}, { name: n+'.y', value: form.clk_y});
  839. }
  840. }
  841. return a;
  842. };
  843. /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&name2=value2 */
  844. $.fn.formSerialize = function(semantic) {
  845. //hand off to jQuery.param for proper encoding
  846. return $.param(this.formToArray(semantic));
  847. };
  848. /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&name2=value2 */
  849. $.fn.fieldSerialize = function(successful) {
  850. var a = [];
  851. this.each(function() {
  852. var n = this.name;
  853. if (!n) {
  854. return;
  855. }
  856. var v = $.fieldValue(this, successful);
  857. if (v && v.constructor == Array) {
  858. for (var i=0,max=v.length; i < max; i++) {
  859. a.push({ name: n, value: v[i]});
  860. }
  861. }
  862. else if (v !== null && typeof v != 'undefined') {
  863. a.push({ name: this.name, value: v});
  864. }
  865. });
  866. //hand off to jQuery.param for proper encoding
  867. return $.param(a);
  868. };
  869. /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */
  870. $.fn.fieldValue = function(successful) {
  871. for (var val=[], i=0, max=this.length; i < max; i++) {
  872. var el = this[i];
  873. var v = $.fieldValue(el, successful);
  874. if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
  875. continue;
  876. }
  877. if (v.constructor == Array) {
  878. $.merge(val, v);
  879. }
  880. else {
  881. val.push(v);
  882. }
  883. }
  884. return val;
  885. };
  886. /** * Returns the value of the field element. */
  887. $.fieldValue = function(el, successful) {
  888. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  889. if (successful === undefined) {
  890. successful = true;
  891. }
  892. if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
  893. (t == 'checkbox' || t == 'radio') && !el.checked ||
  894. (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
  895. tag == 'select' && el.selectedIndex == -1)) {
  896. return null;
  897. }
  898. if (tag == 'select') {
  899. var index = el.selectedIndex;
  900. if (index < 0) {
  901. return null;
  902. }
  903. var a = [], ops = el.options;
  904. var one = (t == 'select-one');
  905. var max = (one ? index+1 : ops.length);
  906. for(var i=(one ? index : 0); i < max; i++) {
  907. var op = ops[i];
  908. if (op.selected) {
  909. var v = op.value;
  910. if (!v) { // extra pain for IE...
  911. v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value;
  912. }
  913. if (one) {
  914. return v;
  915. }
  916. a.push(v);
  917. }
  918. }
  919. return a;
  920. }
  921. return $(el).val();
  922. };
  923. /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */
  924. $.fn.clearForm = function(includeHidden) {
  925. return this.each(function() {
  926. $('input,select,textarea', this).clearFields(includeHidden);
  927. });
  928. };
  929. /** * Clears the selected form elements. */
  930. $.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
  931. var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
  932. return this.each(function() {
  933. var t = this.type, tag = this.tagName.toLowerCase();
  934. if (re.test(t) || tag == 'textarea') {
  935. this.value = '';
  936. }
  937. else if (t == 'checkbox' || t == 'radio') {
  938. this.checked = false;
  939. }
  940. else if (tag == 'select') {
  941. this.selectedIndex = -1;
  942. }
  943. else if (t == "file") {
  944. if (/MSIE/.test(navigator.userAgent)) {
  945. $(this).replaceWith($(this).clone(true));
  946. } else {
  947. $(this).val('');
  948. }
  949. }
  950. else if (includeHidden) {
  951. // includeHidden can be the value true, or it can be a selector string
  952. // indicating a special test; for example:
  953. // $('#myForm').clearForm('.special:hidden')
  954. // the above would clean hidden inputs that have the class of 'special'
  955. if ( (includeHidden === true && /hidden/.test(t)) ||
  956. (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
  957. this.value = '';
  958. }
  959. }
  960. });
  961. };
  962. /** * Resets the form data. Causes all form elements to be reset to their original value. */
  963. $.fn.resetForm = function() {
  964. return this.each(function() {
  965. // guard against an input with the name of 'reset'
  966. // note that IE reports the reset function as an 'object'
  967. if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
  968. this.reset();
  969. }
  970. });
  971. };
  972. /** * Enables or disables any matching elements. */
  973. $.fn.enable = function(b) {
  974. if (b === undefined) {
  975. b = true;
  976. }
  977. return this.each(function() {
  978. this.disabled = !b;
  979. });
  980. };
  981. /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */
  982. $.fn.selected = function(select) {
  983. if (select === undefined) {
  984. select = true;
  985. }
  986. return this.each(function() {
  987. var t = this.type;
  988. if (t == 'checkbox' || t == 'radio') {
  989. this.checked = select;
  990. }
  991. else if (this.tagName.toLowerCase() == 'option') {
  992. var $sel = $(this).parent('select');
  993. if (select && $sel[0] && $sel[0].type == 'select-one') {
  994. // deselect all other options
  995. $sel.find('option').selected(false);
  996. }
  997. this.selected = select;
  998. }
  999. });
  1000. };
  1001. // expose debug var
  1002. $.fn.ajaxSubmit.debug = false;
  1003. // helper fn for console logging
  1004. function log() {
  1005. if (!$.fn.ajaxSubmit.debug) {
  1006. return;
  1007. }
  1008. var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
  1009. if (window.console && window.console.log) {
  1010. window.console.log(msg);
  1011. }
  1012. else if (window.opera && window.opera.postError) {
  1013. window.opera.postError(msg);
  1014. }
  1015. }
  1016. }));

3. 后台处理

  1. /** *@author Fang *@create 2018/10/27 10:22 *@desc 添加 **/
  2. @PostMapping("/addproduct")
  3. public ResponseEntity<Void> addproduct(MultipartFile multipartFile ,Product product){
  4. //上传图片
  5. // 1 获取tomcat的绝对路径
  6. // ServletContext application = request.getServletContext();
  7. String savePath= "F:\\upload";
  8. //判断是否存在
  9. File saveFile = new File(savePath);
  10. if (!saveFile.exists()){
  11. saveFile.mkdir();
  12. }
  13. //脱去 tomcat 的相对路径
  14. String saveUrl= request.getContextPath()+"/upload";
  15. //随机文件名
  16. //获取文件的名字
  17. String filename = multipartFile.getOriginalFilename();
  18. //获取文件的后缀名
  19. String ext = filename.substring(filename.lastIndexOf("."));
  20. //随机文件名
  21. String newFileName=UUID.randomUUID().toString()+ ext;
  22. //组装新的地址
  23. savePath+="/"+newFileName;
  24. File newFile = new File(savePath);
  25. try {
  26. multipartFile.transferTo(newFile);
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. //把地址给promotion
  31. saveUrl+="/"+newFileName;
  32. product.setPimge(saveUrl);
  33. String url = "http://127.0.0.1:8090/product02/addproduct02";
  34. restTemplate.postForEntity(url,product,String.class);
  35. return new ResponseEntity(HttpStatus.OK);
  36. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,215人围观)

还没有评论,来说两句吧...

相关阅读

    相关 图片

    上篇博客已经介绍了文件的上传,这次就简单总结一下图片的上传,以及上传图片的显示。 利用三个控件:Input(File)、Button控件、Image控件,页面简单设计如下图:

    相关 图片

    开发工具与关键技术:Visual Studio 作者:肖广斌 撰写时间:2019年5月12日 在做项目时,我们在完善一些个人信息、或者一些页面时,我们需要用到图片,