diff --git a/flx-ai/pom.xml b/flx-ai/pom.xml index 49ba9e5..9ae1957 100644 --- a/flx-ai/pom.xml +++ b/flx-ai/pom.xml @@ -43,12 +43,12 @@ org.springframework.boot - spring-boot-starter-test - test + spring-boot-starter-web org.springframework.boot - spring-boot-starter-web + spring-boot-starter-test + test org.springframework.boot @@ -154,6 +154,16 @@ hanlp portable-1.8.6 + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-fileupload + commons-fileupload + 1.3 + diff --git a/flx-ai/src/main/java/com/pjilisense/flxai/config/WebMvcConfig.java b/flx-ai/src/main/java/com/pjilisense/flxai/config/WebMvcConfig.java index 4d44d07..c5d1626 100644 --- a/flx-ai/src/main/java/com/pjilisense/flxai/config/WebMvcConfig.java +++ b/flx-ai/src/main/java/com/pjilisense/flxai/config/WebMvcConfig.java @@ -34,6 +34,7 @@ import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; /** * MVC配置 * @@ -89,4 +90,11 @@ public class WebMvcConfig implements WebMvcConfigurer { converter.setObjectMapper(mapper); return converter; } + +// @Bean +// public CommonsMultipartResolver multipartResolver() { +// org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); +// multipartResolver.setMaxUploadSize(100000); // 设置最大上传大小 +// return multipartResolver; +// } } \ No newline at end of file diff --git a/flx-ai/src/main/java/com/pjilisense/flxai/controller/DigitalImgController.java b/flx-ai/src/main/java/com/pjilisense/flxai/controller/DigitalImgController.java index 2ce3e8e..9cd832f 100644 --- a/flx-ai/src/main/java/com/pjilisense/flxai/controller/DigitalImgController.java +++ b/flx-ai/src/main/java/com/pjilisense/flxai/controller/DigitalImgController.java @@ -14,10 +14,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; import springfox.documentation.annotations.ApiIgnore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; @@ -46,7 +48,7 @@ public class DigitalImgController { @Autowired FileUtil fileUtil; @PostMapping("/uploadPicture") - public Result uploadPicture(@RequestParam("file") MultipartFile file) { + public Result uploadPicture(@RequestParam(value="file") MultipartFile file) { if (file.isEmpty()) { return new Result().error("文件为空"); } @@ -57,7 +59,7 @@ public class DigitalImgController { return new Result().error("上传失败: " + e.getMessage()); } } - @PostMapping("/getPicture") + @GetMapping("/getPicture") public void getPicture(HttpServletResponse response,@RequestParam(name = "id", required = true) String id) { try { DigitalImgDTO data = digitalImgService.get(id); @@ -104,6 +106,8 @@ public class DigitalImgController { digitalImgService.save(dto); return new Result(); + //param ={"imgPath":"uploads/202503/5c799cffa5864619b817063f77fe734d..png","name":"开源项目","imgType":"1"} + //{"code":0,"msg":"success","data":null} } @PutMapping diff --git a/flx-ai/src/main/java/com/pjilisense/flxai/utils/FileUtil.java b/flx-ai/src/main/java/com/pjilisense/flxai/utils/FileUtil.java index 6910cdb..618acb1 100644 --- a/flx-ai/src/main/java/com/pjilisense/flxai/utils/FileUtil.java +++ b/flx-ai/src/main/java/com/pjilisense/flxai/utils/FileUtil.java @@ -39,7 +39,7 @@ public class FileUtil { //⽂件后缀,如.jpeg assert filename != null; String suffix = filename.substring(filename.lastIndexOf(".")); - relPath =relPath+"/"+UUID.randomUUID().toString().replace("-","")+"."+suffix; + relPath =relPath+UUID.randomUUID().toString().replace("-","")+suffix; //⽬标⽂件 File descFile = new File(getFilepath(relPath)); //判断⽬标⽂件所在的⽬录是否存在 @@ -92,10 +92,14 @@ public class FileUtil { try { // 读到流中 if(file.isDirectory()) { - inputStream = new FileInputStream(filepath +"/"+ filename);// 文件的存放路径 + filename = rootPath +"/"+ filename; + filename = filename.replace("//","/"); + inputStream = new FileInputStream(filename);// 文件的存放路径 } else { - inputStream = new FileInputStream(filepath);//filepath可能包含文件名 + filename=rootPath; + inputStream = new FileInputStream(filename);//filepath可能包含文件名 } + filename =filename.substring(filename.lastIndexOf("/")+1); response.reset(); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8")); @@ -107,6 +111,7 @@ public class FileUtil { outputStream.write(b, 0, len); } } catch (IOException e) { + System.out.println(e.getMessage()); //log.error(e.getMessage(), e); }finally { try { @@ -117,6 +122,7 @@ public class FileUtil { } } } + // } public String getFilepath (final String filepath) {//filepath可能包含文件名 diff --git a/flx-ai/src/test/java/test/com/pjilisense/flxai/TestUtils.java b/flx-ai/src/test/java/test/com/pjilisense/flxai/TestUtils.java index 5143919..cc54ced 100644 --- a/flx-ai/src/test/java/test/com/pjilisense/flxai/TestUtils.java +++ b/flx-ai/src/test/java/test/com/pjilisense/flxai/TestUtils.java @@ -222,6 +222,40 @@ public class TestUtils { return null; } + public static void doGetFile(String connectURL, String destFile) { + byte[] bytes = null; + ByteArrayOutputStream byteArrayOut = null; + URL url = null; + HttpURLConnection httpGet = null; + InputStream in = null; + try { + url = new URL(connectURL); + httpGet = (HttpURLConnection) url.openConnection(); + httpGet.setConnectTimeout(CONNECT_TIMEOUT); + httpGet.setReadTimeout(READ_TIMEOUT); + httpGet.setRequestProperty("token", TOKEN); + httpGet.connect(); + in = httpGet.getInputStream(); + byteArrayOut = new ByteArrayOutputStream(); + byte[] buf = new byte[512]; + int l = 0; + while ((l = in.read(buf)) != -1) { + byteArrayOut.write(buf, 0, l); + } + bytes = byteArrayOut.toByteArray(); + File file=new File(destFile); + file.getParentFile().mkdirs(); + FileOutputStream fos = new FileOutputStream(file); + fos.write(bytes); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + close(byteArrayOut); + close(in); + close(httpGet); + } + } private static void close(Closeable stream) { if (stream != null) { try { diff --git a/flx-ai/src/test/java/test/com/pjilisense/flxai/controller/DigitalImgControllerTest.java b/flx-ai/src/test/java/test/com/pjilisense/flxai/controller/DigitalImgControllerTest.java new file mode 100644 index 0000000..76f53a4 --- /dev/null +++ b/flx-ai/src/test/java/test/com/pjilisense/flxai/controller/DigitalImgControllerTest.java @@ -0,0 +1,145 @@ +package test.com.pjilisense.flxai.controller; + +import cn.hutool.http.body.MultipartBody; +import com.alibaba.fastjson.JSON; +import io.swagger.annotations.ApiModelProperty; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import test.com.pjilisense.flxai.TestUtils; + +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +public class DigitalImgControllerTest { + + @BeforeEach + public void setUpTestDataWithinTransaction() { + // set up test data within the transaction + } + @AfterEach + public void tearDownWithinTransaction() { + // execute "tear down" logic within the transaction + } + + @Test + public void testuploadPicture() { + String urls = TestUtils.WebconnectURL+"/api/robot/digitalimg/uploadPicture"; + String charset = TestUtils.UTF8; + try { + CloseableHttpClient client = HttpClients.createDefault(); + File file = new File("C:\\Users\\john\\Desktop\\30_200_200.jpg"); + try { + URL url = new URL(urls); + HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); + httpConn.setUseCaches(false); + httpConn.setDoOutput(true); // Indicates that data will be sent + httpConn.setDoInput(true); // Indicates that data will be received + httpConn.setRequestMethod("POST"); // HTTP Request Method + String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate any random value here + httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); + + OutputStream output = httpConn.getOutputStream(); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); + + // Send normal form data with name "file" + writer.append("--" + boundary).append("\r\n"); + writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n"); + writer.append("Content-Type: " + "application/octet-stream").append("\r\n"); + writer.append("\r\n").flush(); + writer.flush(); + + // files data + FileInputStream input = new FileInputStream(file); + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = input.read(buffer)) != -1) { + output.write(buffer, 0, bytesRead); + } + output.flush(); + input.close(); + + // Send multipart form data terminator + writer.append("\r\n").flush(); + writer.append("--" + boundary + "--\r\n").append("\r\n").flush(); + + // Gets the response status code + int status = httpConn.getResponseCode(); + BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + System.out.println(line); + } + writer.close(); + output.close(); + httpConn.disconnect(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } catch (Exception e) { + e.printStackTrace(); + } + //{"code":0,"msg":"success","data":"uploads/202503/882d8b1d82de42308142f9a49b5716f8.jpg"} + } + @Test + public void testgetPicture() { + String url = TestUtils.WebconnectURL+"/api/robot/digitalimg/getPicture?id=1896743235380944897"; + TestUtils.doGetFile(url, "D:\\ceshi\\sysfile\\download\202503\\1896743235380944897.png"); + } + @Test + public void testGetAllAiTools() { + String url = TestUtils.WebconnectURL+"/api/robot/digitalimg/getAllByType?imgType=1"; + String charset = TestUtils.UTF8; + try { + String body = TestUtils.doGet(url, charset); + System.out.println(body); + } catch (Exception e) { + e.printStackTrace(); + } + //{"code":0,"msg":"success","data":[{"id":"1896741333490540546","name":"开源项目","imgPath":"uploads/202503/5c799cffa5864619b817063f77fe734d.png","imgType":"1"}]} + } + @Test + public void testSave() { + String url = TestUtils.WebconnectURL+"/api/robot/digitalimg"; + String charset = TestUtils.UTF8; + try { + Map params = new HashMap(); +// params.put("name","开源项目"); +// params.put("imgPath","uploads/202503/5c799cffa5864619b817063f77fe734d.png"); +// params.put("imgType","1"); + params.put("name","开源项目"); + params.put("imgPath","uploads/202503/d1f8398f9bb844079f774ef496347e12.png"); + params.put("imgType","1"); + String body = TestUtils.doPost(url, JSON.toJSONString(params), charset); + System.out.println(body); + //param ={"imgPath":"uploads/202503/d1f8398f9bb844079f774ef496347e12.png","name":"开源项目","imgType":"1"} + //{"code":0,"msg":"success","data":null} + } catch (Exception e) { + e.printStackTrace(); + } + } + @Test + public void testupdate() { + String url = TestUtils.WebconnectURL+"/api/robot/digitalimg"; + String charset = TestUtils.UTF8; + try { + Map params = new HashMap(); + params.put("id","1896741333490540546"); + params.put("name","开源项目2"); + params.put("imgPath","uploads/202503/5c799cffa5864619b817063f77fe734d.png"); + params.put("imgType","2"); + String body = TestUtils.doPut(url, JSON.toJSONString(params), charset); + System.out.println(body); + //param ={"imgPath":"uploads/202503/5c799cffa5864619b817063f77fe734d.png","name":"开源项目2","id":"1896741333490540546","imgType":"2"} + //{"code":0,"msg":"success","data":null} + } catch (Exception e) { + e.printStackTrace(); + } + } +}