1515package apijson .boot ;
1616
1717import java .io .*;
18+ import java .net .HttpURLConnection ;
19+ import java .net .URL ;
1820import java .net .URLEncoder ;
1921import java .text .DateFormat ;
2022import java .util .*;
@@ -125,15 +127,46 @@ public boolean accept(File file) {
125127
126128 @ PostMapping (value = "/upload" , consumes = MediaType .MULTIPART_FORM_DATA_VALUE )
127129 @ ResponseBody
128- public JSONObject upload (@ RequestParam ("file" ) MultipartFile file ) {
130+ public JSONObject upload (
131+ @ RequestParam (value = "file" , required = false ) MultipartFile file ,
132+ @ RequestParam (value = "url" , required = false ) String url
133+ ) {
129134 try {
130- String name = file .getOriginalFilename ();
131- name = (StringUtil .isEmpty (name ) ? DateFormat .getDateInstance ().format (new Date ()) : name )
132- .replaceAll ("[^a-zA-Z0-9._-]" , String .valueOf (Math .round (1100 *Math .random ())));
135+ byte [] bytes ;
136+ String name ;
137+ // 1 如果是文件上传
138+ if (file != null && !file .isEmpty ()) {
139+ bytes = file .getBytes ();
140+ name = file .getOriginalFilename ();
141+ }
142+ // 2 如果是 URL 上传
143+ else if (url != null && url .startsWith ("http" )) {
144+ URL imageUrl = new URL (url );
145+ HttpURLConnection conn = (HttpURLConnection ) imageUrl .openConnection ();
146+ conn .setConnectTimeout (10000 );
147+ conn .setReadTimeout (10000 );
148+ conn .setRequestProperty ("User-Agent" , "Mozilla/5.0" );
149+
150+ InputStream in = conn .getInputStream ();
151+ bytes = in .readAllBytes ();
152+ in .close ();
153+
154+ name = new File (imageUrl .getPath ()).getName ();
155+ }
156+ else {
157+ throw new RuntimeException ("file or url required" );
158+ }
159+
160+ // 3 文件名处理
161+ name = (StringUtil .isEmpty (name )
162+ ? DateFormat .getDateInstance ().format (new Date ())
163+ : name )
164+ .replaceAll ("[^a-zA-Z0-9._-]" , String .valueOf (Math .round (1100 * Math .random ())));
165+
166+ // 4 写入文件
133167 File convertFile = new File (fileUploadRootDir + name );
134- FileOutputStream fileOutputStream ;
135- fileOutputStream = new FileOutputStream (convertFile );
136- fileOutputStream .write (file .getBytes ());
168+ FileOutputStream fileOutputStream = new FileOutputStream (convertFile );
169+ fileOutputStream .write (bytes );
137170 fileOutputStream .close ();
138171
139172 if (fileNames != null && ! fileNames .isEmpty ()) {
@@ -142,9 +175,10 @@ public JSONObject upload(@RequestParam("file") MultipartFile file) {
142175
143176 JSONObject res = new JSONObject ();
144177 res .put ("path" , "/download/" + name );
145- res .put ("size" , file . getBytes () .length );
178+ res .put ("size" , bytes .length );
146179 return new DemoParser ().extendSuccessResult (res );
147- }
180+
181+ }
148182 catch (Exception e ) {
149183 e .printStackTrace ();
150184 return new DemoParser ().newErrorResult (e );
0 commit comments