Parcourir la source

文件下载,图片信息

mxd il y a 4 ans
Parent
commit
c234613cb4

+ 4 - 0
src/main/java/org/ssssssss/magicapi/config/RequestHandler.java

@@ -2,6 +2,7 @@ package org.ssssssss.magicapi.config;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -86,6 +87,9 @@ public class RequestHandler {
 					return target;
 				}
 			}
+			if(value instanceof ResponseEntity){
+				return value;
+			}
 			return resultProvider.buildResult(value);
 		} catch (Throwable root) {
 			if (throwException) {

+ 33 - 1
src/main/java/org/ssssssss/magicapi/config/WebUIController.java

@@ -1,9 +1,14 @@
 package org.ssssssss.magicapi.config;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.MDC;
+import org.springframework.core.io.InputStreamSource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
@@ -24,7 +29,9 @@ import org.ssssssss.script.exception.MagicScriptException;
 import org.ssssssss.script.parsing.Span;
 
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
+import java.io.InputStream;
 import java.util.*;
 
 /**
@@ -262,7 +269,7 @@ public class WebUIController {
 	 */
 	@RequestMapping("/test")
 	@ResponseBody
-	public JsonBean<Object> test(HttpServletRequest servletRequest, @RequestBody(required = false) Map<String, Object> request) {
+	public Object test(HttpServletRequest servletRequest, @RequestBody(required = false) Map<String, Object> request, HttpServletResponse response) {
 		if (!allowVisit(servletRequest, RequestInterceptor.Authorization.RUN)) {
 			return new JsonBean<>(-10, "无权限执行测试方法");
 		}
@@ -298,6 +305,16 @@ public class WebUIController {
 				} else if (context.isException()) {    //判断是否出现异常
 					return resolveThrowable((Throwable) context.getReturnValue());
 				}
+				if (result instanceof ResponseEntity) {
+					ResponseEntity entity = (ResponseEntity) result;
+					for (Map.Entry<String, List<String>> entry : entity.getHeaders().entrySet()) {
+						String key = entry.getKey();
+						for (String value : entry.getValue()) {
+							response.addHeader("MA-" + key, value);
+						}
+					}
+					return ResponseEntity.ok(new JsonBean<>(convertToBase64(entity.getBody())));
+				}
 				return new JsonBean<>(resultProvider.buildResult(result));
 			} catch (Exception e) {
 				return resolveThrowable(e);
@@ -306,6 +323,21 @@ public class WebUIController {
 		return new JsonBean<>(resultProvider.buildResult(0, "脚本不能为空"));
 	}
 
+	private String convertToBase64(Object value) throws IOException {
+		if(value instanceof String || value instanceof Number){
+			return convertToBase64(value.toString().getBytes());
+		}else if(value instanceof byte[]){
+			return Base64.getEncoder().encodeToString((byte[]) value);
+		}else if(value instanceof InputStream){
+			return convertToBase64(IOUtils.toByteArray((InputStream) value));
+		}else if(value instanceof InputStreamSource){
+			InputStreamSource iss = (InputStreamSource) value;
+			return convertToBase64(iss.getInputStream());
+		}else {
+			return convertToBase64(new ObjectMapper().writeValueAsString(value));
+		}
+	}
+
 	/**
 	 * 解决异常
 	 */

+ 41 - 4
src/main/java/org/ssssssss/magicapi/functions/ResponseFunctions.java

@@ -1,7 +1,12 @@
 package org.ssssssss.magicapi.functions;
 
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.ssssssss.magicapi.provider.ResultProvider;
 
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
 import java.util.List;
 
 public class ResponseFunctions {
@@ -14,10 +19,42 @@ public class ResponseFunctions {
 
 	/**
 	 * 自行构建分页结果
-	 * @param total	条数
-	 * @param values	数据内容
+	 *
+	 * @param total  条数
+	 * @param values 数据内容
 	 */
-	public Object page(long total, List<Object> values){
-		return resultProvider.buildPageResult(total,values);
+	public Object page(long total, List<Object> values) {
+		return resultProvider.buildPageResult(total, values);
+	}
+
+	/**
+	 * 自定义json结果
+	 *
+	 * @param value json内容
+	 */
+	public ResponseEntity json(Object value) {
+		return ResponseEntity.ok(value);
+	}
+
+	/**
+	 * 展示图片
+	 *
+	 * @param value 图片内容
+	 * @param mime  图片类型,image/png,image/jpeg,image/gif
+	 */
+	public ResponseEntity image(Object value, String mime) {
+		return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, mime).body(value);
+	}
+
+	/**
+	 * 文件下载
+	 *
+	 * @param value    文件内容
+	 * @param filename 文件名
+	 */
+	public ResponseEntity download(Object value, String filename) throws UnsupportedEncodingException {
+		return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM)
+				.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"))
+				.body(value);
 	}
 }

+ 40 - 8
src/main/resources/magicapi-support/js/index.js

@@ -410,9 +410,9 @@ var MagicEditor = {
             dataType : 'json',
             contentType : options.contentType,
             data : options.data,
-            success : function(json){
+            success : function(json,data,xhr){
                 if(json.code == 1){
-                    options&&options.success(json.data,json);
+                    options&&options.success(json.data,json,xhr);
                 }else{
                     var val = options.exception&&options.exception(json.code,json.message,json);
                     if(val !== false){
@@ -449,8 +449,8 @@ var MagicEditor = {
                 data : {
                     id : this.debugSessionId
                 },
-                success : function(data,json){
-                    _this.convertResult(json.code,json.message,json);
+                success : function(data,json,xhr){
+                    _this.convertResult(json.code,json.message,json,xhr);
                 },
                 exception : function(code,message,json){
                     return _this.convertResult(code,message,json);
@@ -554,8 +554,8 @@ var MagicEditor = {
                 url : 'test',
                 data : JSON.stringify(request),
                 contentType : 'application/json;charset=utf-8',
-                success : function(data,json){
-                    _this.convertResult(json.code,json.message,json);
+                success : function(data,json,xhr){
+                    _this.convertResult(json.code,json.message,json,xhr);
                 },
                 exception : function(code,message,json){
                     return _this.convertResult(code,message,json);
@@ -628,7 +628,7 @@ var MagicEditor = {
             }
         })
     },
-    convertResult : function(code,message,json){
+    convertResult : function(code,message,json,xhr){
         this.debugSessionId = null;
         this.resetDebugContent();
         this.debugDecorations&&this.scriptEditor&&this.scriptEditor.deltaDecorations(this.debugDecorations,[]);
@@ -668,7 +668,39 @@ var MagicEditor = {
         $(".button-run").removeClass('disabled');
         $('.button-continue').addClass('disabled');
         this.navigateTo(2)
-        var outputJson = this.formatJson(json.data);
+        var outputJson;
+        var contentType = xhr&&xhr.getResponseHeader('ma-content-type');
+        if(contentType == 'application/octet-stream'){  //文件下载
+            var disposition = xhr.getResponseHeader('ma-content-disposition');
+            var filename = 'output';
+            if(disposition){
+                filename = disposition.substring(disposition.indexOf('filename=') + 9);
+            }
+            outputJson = this.formatJson({
+                filename : filename
+            });
+            var a = document.createElement("a");
+            a.download = filename;
+            var bstr = atob(json.data);
+            var n = bstr.length;
+            var u8arr = new Uint8Array(n);
+            while (n--) {
+                u8arr[n] = bstr.charCodeAt(n);
+            }
+            a.href = window.URL.createObjectURL(new Blob([u8arr]));
+            a.click();
+        }else if(contentType.indexOf('image') == 0){    //image开头
+            outputJson = this.formatJson(json.data);
+            this.createDialog({
+                title : '图片结果',
+                content : '<p align="center"><img  src="data:'+contentType+';base64,'+json.data+'"></p>',
+                replace : false,
+                buttons : [{name : 'OK'}]
+            })
+        }else{
+            outputJson = this.formatJson(json.data);
+        }
+
         this.outputJson = outputJson;
         this.resultEditor.setValue(outputJson);
         return ret;