Эх сурвалжийг харах

Added Drag & Drop browser file upload demo based on filedropjs.org

Pierre-Olivier Latour 11 жил өмнө
parent
commit
b42daf1e14

+ 24 - 0
GCDWebServer.xcodeproj/project.pbxproj

@@ -79,6 +79,8 @@
 		E22112981690B7AA0048D2B2 /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; };
 		E221129A1690B7B10048D2B2 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; };
 		E221129C1690B7BA0048D2B2 /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/System/Library/Frameworks/MobileCoreServices.framework; sourceTree = DEVELOPER_DIR; };
+		E263213318DB688E00D9DC0C /* index.html */ = {isa = PBXFileReference; lastKnownFileType = text.html; path = index.html; sourceTree = "<group>"; };
+		E263213418DB7F7900D9DC0C /* filedrop-min.js */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.javascript; path = "filedrop-min.js"; sourceTree = "<group>"; };
 /* End PBXFileReference section */
 
 /* Begin PBXFrameworksBuildPhase section */
@@ -145,6 +147,8 @@
 		E221128D1690B6470048D2B2 /* Mac */ = {
 			isa = PBXGroup;
 			children = (
+				E263213418DB7F7900D9DC0C /* filedrop-min.js */,
+				E263213318DB688E00D9DC0C /* index.html */,
 				E221128E1690B6470048D2B2 /* main.m */,
 			);
 			path = Mac;
@@ -293,6 +297,16 @@
 			buildSettings = {
 				ARCHS = "$(ARCHS_STANDARD)";
 				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				OTHER_LDFLAGS = (
+					"-sectcreate",
+					__TEXT,
+					_index_html_,
+					"\"Mac/index.html\"",
+					"-sectcreate",
+					__TEXT,
+					_filedrop_js_,
+					"\"Mac/filedrop-min.js\"",
+				);
 				PRODUCT_NAME = GCDWebServer;
 				SDKROOT = macosx;
 			};
@@ -303,6 +317,16 @@
 			buildSettings = {
 				ARCHS = "$(ARCHS_STANDARD)";
 				MACOSX_DEPLOYMENT_TARGET = 10.7;
+				OTHER_LDFLAGS = (
+					"-sectcreate",
+					__TEXT,
+					_index_html_,
+					"\"Mac/index.html\"",
+					"-sectcreate",
+					__TEXT,
+					_filedrop_js_,
+					"\"Mac/filedrop-min.js\"",
+				);
 				PRODUCT_NAME = GCDWebServer;
 				SDKROOT = macosx;
 			};

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 8 - 0
Mac/filedrop-min.js


+ 91 - 0
Mac/index.html

@@ -0,0 +1,91 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>Basic FileDrop example</title>
+
+    <script type="text/javascript" src="filedrop-min.js"></script>
+
+    <style type="text/css">
+
+    /* Essential FileDrop zone element configuration: */
+    .fd-zone {
+      position: relative;
+      overflow: hidden;
+      /* The following are not required but create a pretty box: */
+      width: 15em;
+      margin: 0 auto;
+      text-align: center;
+    }
+
+    /* Hides <input type="file"> while simulating "Browse" button: */
+    .fd-file {
+      opacity: 0;
+      font-size: 118px;
+      position: absolute;
+      right: 0;
+      top: 0;
+      z-index: 1;
+      padding: 0;
+      margin: 0;
+      cursor: pointer;
+      filter: alpha(opacity=0);
+      font-family: sans-serif;
+    }
+
+    /* Provides visible feedback when use drags a file over the drop zone: */
+    .fd-zone.over { border-color: maroon; background: #eee; }
+
+    </style>
+  </head>
+  <body>
+
+    <noscript style="color: maroon">
+      <h2>JavaScript is disabled in your browser. How do you expect FileDrop to work?</h2>
+    </noscript>
+
+    <h2 style="text-align: center">
+      <a href="http://filedropjs.org">FileDrop</a> basic sample
+    </h2>
+
+    <!-- A FileDrop area. Can contain any text or elements, or be empty.
+         Can be of any HTML tag too, not necessary fieldset. -->
+    <fieldset id="zone">
+      <legend>Drop a file inside&hellip;</legend>
+      <p>Or click here to <em>Browse</em>..</p>
+
+      <!-- Putting another element on top of file input so it overlays it
+           and user can interact with it freely. -->
+      <p style="z-index: 10; position: relative">
+        <input type="checkbox" id="multiple">
+        <label for="multiple">Allow multiple selection</label>
+      </p>
+    </fieldset>
+
+    <script type="text/javascript">
+      // Attach FileDrop to an area ('zone' is an ID but you can also give a DOM node):
+      var zone = new FileDrop('zone', {});
+
+      // Do something when a user chooses or drops a file:
+      zone.event('send', function (files) {
+        // Depending on browser support files (FileList) might contain multiple items.
+        files.each(function (file) {
+          // React on successful AJAX upload:
+          file.event('done', function (xhr) {
+            // 'this' here points to fd.File instance that has triggered the event.
+            alert('Done uploading ' + this.name + ', response:\n\n' + xhr.responseText);
+          });
+
+          // Send the file:
+          file.sendTo('ajax-upload');
+        });
+      });
+
+      // A bit of sugar - toggling multiple selection:
+      fd.addEvent(fd.byID('multiple'), 'change', function (e) {
+        zone.multiple(e.currentTarget || e.srcElement.checked);
+      });
+    </script>
+
+  </body>
+</html>

+ 39 - 1
Mac/main.m

@@ -25,11 +25,22 @@
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#import <mach-o/getsect.h>
+
 #import "GCDWebServer.h"
 
+static NSData* _DataFromTEXTSection(const char* name) {
+  unsigned long size = 0;
+  char* ptr = getsectdata("__TEXT", name, &size);
+  if (!ptr || !size) {
+    abort();
+  }
+  return [NSData dataWithBytesNoCopy:ptr length:size freeWhenDone:NO];
+}
+
 int main(int argc, const char* argv[]) {
   BOOL success = NO;
-  int mode = (argc == 2 ? MIN(MAX(atoi(argv[1]), 0), 2) : 0);
+  int mode = (argc == 2 ? MIN(MAX(atoi(argv[1]), 0), 3) : 0);
   @autoreleasepool {
     GCDWebServer* webServer = [[GCDWebServer alloc] init];
     switch (mode) {
@@ -83,6 +94,33 @@ int main(int argc, const char* argv[]) {
         break;
       }
       
+      // Implements drag & drop file upload using http://filedropjs.org (requires Chrome 13+, Firefox 3.6+, IE 10+ or Safari 6+)
+      case 3: {
+        [webServer addGETHandlerForPath:@"/"
+                             staticData:_DataFromTEXTSection("_index_html_")
+                            contentType:@"text/html; charset=utf-8"
+                               cacheAge:0];
+        [webServer addGETHandlerForPath:@"/filedrop-min.js"
+                             staticData:_DataFromTEXTSection("_filedrop_js_")
+                            contentType:@"application/javascript; charset=utf-8"
+                               cacheAge:0];
+        [webServer addHandlerForMethod:@"POST" path:@"/ajax-upload" requestClass:[GCDWebServerFileRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
+          
+          NSString* fileName = GCDWebServerUnescapeURLString([request.headers objectForKey:@"X-File-Name"]);
+          NSString* inPath = [(GCDWebServerFileRequest*)request filePath];
+          NSString* outPath = [@"/tmp" stringByAppendingPathComponent:fileName];
+          [[NSFileManager defaultManager] removeItemAtPath:outPath error:NULL];
+          if ([[NSFileManager defaultManager] moveItemAtPath:inPath toPath:outPath error:NULL]) {
+            NSString* message = [NSString stringWithFormat:@"File uploaded to \"%@\"", outPath];
+            return [GCDWebServerDataResponse responseWithText:message];
+          } else {
+            return [GCDWebServerResponse responseWithStatusCode:500];
+          }
+          
+        }];
+        break;
+      }
+      
     }
     success = [webServer runWithPort:8080];
 #if !__has_feature(objc_arc)

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно