How to add a already loaded image into browser, into a form field of type 'file'.


/ Published in: HAML

This code can collect and Date and Description from user, then User can drag/drop an image in drop area to load it into browser OR if browser doesn't support drag/drop, then user can see a normal file input instead to browse and choose an image. after that user can determine a crop area for corresponding image. until here everything works charming. If I use a file input as a form field, after submit, in controller function ( by using WebImage static methods) I can get all images existing in request easily. Problem is when I use a drag/drop method to load a image in browser. then there is no File object in Request to could be retrieved in Controller using WebImage methods.
How can I add this File object somehow to Request?
I can't use Ajax because sometimes user needs to load image in browser and determine a Crop area for that.


Copy this code and paste it in your HTML
  1. @model Progresspics_b14.Models.Level
  2.  
  3. @{
  4. ViewBag.Title = "Create";
  5. }
  6.  
  7. function previewfile(file) {
  8. if (tests.filereader === true && acceptedTypes[file.type] === true) {
  9. var reader = new FileReader();
  10. reader.onload = function (event) {
  11. var image = new Image();
  12. image.id = "imgcrop";
  13. image.src = event.target.result;
  14.  
  15. // 'holder' always is holding only one image. If drag/drop multiple files, then only one last file will be holding there.
  16. // if there is already an image holded in 'holder', by drag/drop new image, old image will be replaced with new one.
  17. while (imageholder.childNodes.length > 0) {
  18. imageholder.removeChild(imageholder.lastChild);
  19. }
  20. imageholder.appendChild(image);
  21.  
  22. api = $.Jcrop('#imgcrop', { onSelect: storeCoords, aspectRatio: 1 / 2, boxWidth: document.getElementById('imageholder').clientWidth });
  23. };
  24.  
  25. reader.readAsDataURL(file);
  26. } else {
  27. holder.innerHTML += '<p>Uploaded ' + file.name + ' ' + (file.size ? (file.size / 1024 | 0) + 'K' : '');
  28. console.log(file);
  29. }
  30. }
  31.  
  32. function storeCoords(c) {
  33. jQuery('#X').val(c.x);
  34. jQuery('#Y').val(c.y);
  35. jQuery('#Z').val(c.w);
  36. jQuery('#A').val(c.h);
  37. }
  38.  
  39. function readfiles(files) {
  40.  
  41. var formData = tests.formdata ? new FormData() : null;
  42. for (var i = 0; i < files.length; i++) {
  43. if (tests.formdata) formData.append('file', files[i]);
  44. previewfile(files[i]);
  45. }
  46.  
  47. //// now post a new XHR request
  48. //if (tests.formdata) {
  49. // var xhr = new XMLHttpRequest();
  50. // xhr.open('POST', '/devnull.php');
  51. // xhr.onload = function() {
  52. // progress.value = progress.innerHTML = 100;
  53. // };
  54.  
  55. // if (tests.progress) {
  56. // xhr.upload.onprogress = function (event) {
  57. // if (event.lengthComputable) {
  58. // var complete = (event.loaded / event.total * 100 | 0);
  59. // progress.value = progress.innerHTML = complete;
  60. // }
  61. // }
  62. // }
  63. // xhr.send(formData);
  64. //}
  65. }
  66. #holder {
  67. border: 2px dashed #898989;
  68. min-height: 50px;
  69. text-align: center;
  70. }
  71.  
  72. #imageholder {
  73. border: 2px solid #ccc;
  74. clear: both; /*min-width: 50px;*/
  75. min-height: 50px; /* margin: 10px auto;*/
  76. }
  77.  
  78. #holder.hover {
  79. border: 5px dashed #0c0;
  80. }
  81.  
  82. #Text { /*width: 220px;*/
  83. margin: 10px auto 0 auto;
  84. position: relative;
  85. text-align: left;
  86. color: #bbb;
  87. font-size: 15px;
  88. }
  89.  
  90. #holder img {
  91. display: block;
  92. margin: 10px auto;
  93. }
  94.  
  95. #holder p {
  96. margin: 10px;
  97. font-size: 14px;
  98. }
  99.  
  100. progress {
  101. width: 100%;
  102. }
  103.  
  104. progress:after {
  105. content: '%';
  106. }
  107.  
  108. .fail {
  109. background: #c00;
  110. padding: 2px;
  111. color: #fff;
  112. }
  113.  
  114. .hidden {
  115. display: none !important;
  116. }
  117.  
  118. <h2>Create</h2>
  119. <br />
  120. <div>
  121. @using (Html.BeginForm("create", "Level", FormMethod.Post, new { id = "upload_form", enctype = "multipart/form-data" }))
  122. {
  123.  
  124. @Html.AntiForgeryToken()
  125. @Html.ValidationSummary(true)
  126.  
  127. <legend>Level</legend>
  128. @Html.HiddenFor(model => model.PostId)
  129.  
  130. <div class="editor-label">
  131. @Html.LabelFor(model => model.LevelDate)
  132. </div>
  133. <div>
  134. <input type="date" id="LevelDate" name="LevelDate" title="Date" />
  135. @Html.ValidationMessageFor(model => model.LevelDate)
  136. </div>
  137.  
  138. <div class="editor-label">
  139. @Html.LabelFor(model => model.Description)
  140. </div>
  141. <div class="editor-field">
  142. @Html.EditorFor(model => model.Description)
  143. @Html.ValidationMessageFor(model => model.Description)
  144. </div>
  145.  
  146. <div id="holder">
  147. <div id="Text">DROP HERE ('jpeg', 'gif', 'png')</div>
  148. </div>
  149. <p id="alt_upload">
  150. Drag & drop not supported, but you can still upload via this input field:<br>
  151. <input type="file" id="uplaod_filedialog">
  152. </label>
  153. </p>
  154. <p id="filereader">File API & FileReader API not supported</p>
  155. <p id="formdata">XHR2's FormData is not supported</p>
  156. <p id="progress">XHR2's upload progress isn't supported</p>
  157.  
  158. <div id="imageholder"></div>
  159.  
  160. <input type="hidden" id="X" />
  161. <input type="hidden" id="Y" />
  162. <input type="hidden" id="Z" />
  163. <input type="hidden" id="A" />
  164.  
  165. <script>
  166. var imageholder = document.getElementById('imageholder'),
  167. holder = document.getElementById('holder'),
  168. tests = {
  169. filereader: typeof FileReader != 'undefined',
  170. dnd: 'draggable' in document.createElement('span'),
  171. formdata: !!window.FormData,
  172. },
  173. support = {
  174. filereader: document.getElementById('filereader'),
  175. formdata: document.getElementById('formdata'),
  176. progress: document.getElementById('progress')
  177. },
  178. acceptedTypes = {
  179. 'image/png': true,
  180. 'image/jpeg': true,
  181. 'image/gif': true
  182. },
  183. fileupload = document.getElementById('alt_upload');
  184.  
  185. "filereader formdata progress".split(' ').forEach(function (api) {
  186. if (tests[api] === false) {
  187. support[api].className = 'fail';
  188. } else {
  189. // I could have done el.hidden = true, but IE doesn't support
  190. // hidden, so I tried to create a polyfill that would extend the
  191. // Element.prototype, but then IE10 doesn't even give me access
  192. // to the Element object. Brilliant.
  193. support[api].className = 'hidden';
  194. }
  195. });
  196.  
  197. if (tests.dnd) {
  198. fileupload.className = 'hidden';
  199. holder.className = '';
  200. holder.ondragover = function () { this.className = 'hover'; return false; };
  201. holder.ondragend = function () { this.className = ''; return false; };
  202. holder.ondrop = function (e) {
  203. this.className = '';
  204. e.preventDefault();
  205. readfiles(e.dataTransfer.files);
  206. $('#upload_form').in {
  207. formData: { example: 'test' }
  208.  
  209. });
  210. };
  211. } else {
  212. holder.className = 'hidden';
  213. fileupload.className = '';
  214. fileupload.querySelector('input').onchange = function () {
  215. readfiles(this.files);
  216. };
  217. }
  218. </script>
  219.  
  220. <p>
  221. <input type="submit" value="Save" />@Html.ActionLink("Back to List", "Index")
  222. </p>
  223.  
  224. }
  225. </div>
  226.  
  227.  
  228. @section Scripts {
  229. @Scripts.Render("~/bundles/jqueryval")
  230. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.