whycrzh
2021-01-28 9f05d9863af714b206bdfffe2096d60a942c9d23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
package com.fgkj.controller;
 
import com.fgkj.dto.*;
import com.fgkj.mapper.UinfDaoFactory;
import com.fgkj.services.User_logService;
import com.fgkj.util.*;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
 
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import javax.annotation.Resource;
 
@RequestMapping("myFile")
@RestController
@Api(tags = "myFile接口")
public class MyFileController{
    
 
    /*private String battname;
    private File[] file;
    // 提交过来的file的名字
    private String[] fileFileName;
    // 提交过来的file的MIME类型
    private String[] fileContentType;
    
    private String filestr;                //文件内容
    private String fname;                //文件内容*/
    
    //上传文件
    @PostMapping("/uploadTestFile")
    @ApiOperation(notes = "",value="byInfo")
    public ServiceModel UploadTestFile(@RequestParam File[] file,String[] fileFileName,String battName){
        HttpServletResponse res = ActionUtil.getResponse();
        res.setHeader("Access-Control-Allow-Origin", "*");                //允许跨域访问
        res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
 
        
        boolean f = createFile(file,fileFileName,battName);
        ServiceModel model = new ServiceModel();
        if(f){
            model.setCode(1);
            model.setMsg("上传成功");
        }else{
            model.setCode(0);
            model.setMsg("上传失败");
        }
        return model;
    }
    
    public boolean createFile(File[] file,String[] fileFileName,String battName){
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();
        boolean flag = false;
        String root = str+"/uploadfiles/";        // 上传路径
        //System.out.println(battname+"***");
        for(int i=0;i<file.length;i++){
            String savepath=root+battName+"/"+fileFileName[i];
            //System.out.println(savepath);
            FileInputStream fis=null;
            FileOutputStream fos=null;
            try {                      
                File f = new File(savepath);
                if(!f.exists()){
                    if(!f.getParentFile().exists()){
                        f.getParentFile().mkdirs();
                    }
                    f.createNewFile();
                }
                /** 创建输入流 */      
                fis = new FileInputStream(file[i]);       
                /** 输出流 根据文件的路径+文件名称创建文件对象 */      
                fos = new FileOutputStream(f);       
                /** 读取字节   */      
                byte b[] = new byte[1024];       
                int n = 0;       
                /** 读取操作   */      
                while ((n = fis.read(b)) != -1) {       
                    /** 写操作   */      
                    fos.write(b, 0, n);       
                }    
                fos.flush();
                flag = true;
            } catch (Exception e) {       
                e.printStackTrace();
            } finally{
                 /** 关闭操作  */      
                try {
                    if (fis != null) {       
                        fis.close();       
                    }       
                    if (fos != null) {       
                        fos.close();       
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag; 
    }
 
    @PostMapping("uploadIphoneFile")
    @ApiOperation(notes = "",value="byInfo")
    public ServiceModel UploadIphoneFile(@RequestParam String filestr,String fname,String battname){
        HttpServletResponse res = ActionUtil.getResponse();
        res.setHeader("Access-Control-Allow-Origin", "*");                //允许跨域访问
        res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        Gson gson = new Gson();
        int[] arr = gson.fromJson(filestr, int[].class);
        
        System.out.println("文件名"+fname);
        System.out.println("文件内容:"+filestr);
        System.out.println("电池组名称"+battname);
        boolean f = createFileByarr(arr,fname,battname);
        
        ServiceModel model = new ServiceModel();
        if(f){
            model.setCode(1);
            model.setMsg("上传成功");
        }else{
            model.setCode(0);
            model.setMsg("上传失败");
        }
        return model;
    }
    
    /**
     * 
     * @param arr            文件的字节数组
     * @param fname            文件名
     * @param bname            电池组名称
     * @return                是否生成文件成功
     */
    public boolean createFileByarr(int[] arr,String fname,String bname){
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();
        boolean flag = false;
        String root = str+"/uploadfiles/";        // 上传路径
        //System.out.println(battname+"***");
        String savepath=root+bname+"/"+fname;
        //System.out.println(savepath);
        FileOutputStream fos=null;
        byte[] bytes = new byte[arr.length];
        for(int i=0;i<arr.length;i++){
            bytes[i] = (byte)(arr[i] & 0xFF);
        }        
        
        try {                      
            File f = new File(savepath);
            if(!f.exists()){
                if(!f.getParentFile().exists()){
                    f.getParentFile().mkdirs();
                }
                f.createNewFile();
            }    
            fos = new FileOutputStream(savepath);
            fos.write(bytes);
            fos.flush();
            flag = true;
        } catch (Exception e) {       
            e.printStackTrace();
        } finally{
             /** 关闭操作  */      
            try {
                if (fos != null) {       
                    fos.close();       
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag; 
    }
    
    //上传机房视频接口
    @PostMapping("uploadStationFile")
    @ApiOperation(notes = "",value="上传机房视频接口")
    public ServiceModel uploadStationFile(@RequestBody BattInf binf,@RequestParam File[] file,String[] fileFileName){
        // BattInf binf = getGson().fromJson(json, BattInf.class);
        String fileRoot = "stationsrc";
        ServiceModel model = new ServiceModel();    
        boolean isSuccess = false;
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();                                                    //获取服务器所在的绝对路径
        String root = str+"/"+fileRoot+"/"+binf.getStationId()+"/"+binf.getVideoOrImage()+"/";                                                    // 上传路径
        for(int i=0;i<file.length && binf != null;i++){
            String filePath = root+fileFileName[i];
            ActionUtil.createFilefolderIFNotExist(filePath);
            copyFile(file[i], filePath);
            isSuccess = true;
        }
        if(isSuccess){
            model.setCode(1);
            model.setMsg("上传成功");
        }else{
            model.setCode(0);
            model.setMsg("上传失败");
        }
 
        return model;
    }
    
    /**
     * 
     *     获取指定机房得资源
     */
    @PostMapping("stationSource")
    @ApiOperation(notes = "",value="获取指定机房得资源")
    public ServiceModel searchStationSource(@RequestBody BattInf binf){
        String fileRoot = "stationsrc";                                                            //存放机房资源文件的文件夹
        // BattInf binf = getGson().fromJson(json, BattInf.class);
        ServiceModel model = new ServiceModel();
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();    
        if(binf != null && binf.getStationId() != null && binf.getVideoOrImage() != null){
            String filesource = str+File.separator+fileRoot+File.separator+binf.getStationId()+File.separator+binf.getVideoOrImage()+File.separator;                //当前请求的机房所在的资源文件夹
            //System.out.println(filesource);
            File source = new File(filesource);
            File[] files = source.listFiles();
            model.setMsg("暂无视频文件");
            if(files!=null && files.length>0){
                List myfiles = new ArrayList<MyFile>();
                for(int i=0;i<files.length;i++){
                    MyFile myfile = new MyFile();
                    if(files[i].isFile()){
                        myfile.setFile(files[i]);
                        if(binf.getVideoOrImage().equals("image")) {
                            myfile.setIms(ImageInfor(files[i]));
                        }
                        myfiles.add(myfile);
                        
                    }
                }
                if(myfiles.size() > 0){
                    model.setCode(1);
                    model.setData(myfiles);
                    model.setMsg("读取成功");
                }
            }
            
        }
 
        return model;
    }
    
    //将文件复制到指定的目录
    public static void copyFile(File oldFile, String newPath){
        File file = new File(newPath);
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(oldFile);
            out = new FileOutputStream(file);;
 
            byte[] buffer=new byte[2097152];
            int readByte = 0;
            while((readByte = in.read(buffer)) != -1){
                out.write(buffer, 0, readByte);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //上传机房视频接口(手机端)
    @PostMapping("uploadStationFile4Mobile")
    @ApiOperation(notes = "",value="上传机房视频接口(手机端)")
    public ServiceModel uploadStationFile_mobile(@RequestBody BattInf binf,@RequestParam File[] file,String[] fileFileName){
        // BattInf binf = getGson().fromJson(json, BattInf.class);
        String fileRoot = "stationsrc";
        ServiceModel model = new ServiceModel();    
        boolean isSuccess = false;
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();                                                    //获取服务器所在的绝对路径
        String root = str+"/"+fileRoot+"/"+binf.getStationId()+"/"+binf.getVideoOrImage()+"/";                                                    // 上传路径
        for(int i=0;i<file.length && binf != null;i++){
            String filePath = root+fileFileName[i];
            ActionUtil.createFilefolderIFNotExist(filePath);
            if(binf.getVideoOrImage().equals("image")) {
                GraphicsFile(binf.getBinfmation(), file[i], filePath);
            }else {
                copyFile(file[i], filePath);
            }
            isSuccess = true;
        }
        if(isSuccess){
            model.setCode(1);
            model.setMsg("上传成功");
        }else{
            model.setCode(0);
            model.setMsg("上传失败");
        }
 
        return model;
    }
    //将获取到得图片加水印
    public static void GraphicsFile(Object obj, File file,String newImagePath) {
        //InputStream is = null;
        OutputStream os = null;
        BattMap_information binfmation=(BattMap_information) obj;
        try {
            // 1、源图片
            java.awt.Image srcImg = ImageIO.read(file);
            //System.out.println(srcImg.);
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), java.awt.Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            /*if (null != degree) {
                //System.out.println("buffImg.getWidth():"+buffImg.getWidth()+"  buffImg.getHeight():"+buffImg.getHeight());
                g.rotate(Math.toRadians(degree),  buffImg.getWidth()/10,buffImg.getHeight() /10);
            }*/
            // 5、设置水印文字颜色
            g.setColor(new Color(255,0,0));//默认红色
            int font_size= buffImg.getHeight() /35;
            // 6、设置水印文字Font
            g.setFont(new java.awt.Font("宋体", java.awt.Font.BOLD,font_size));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
            //设置经度
            g.drawString("经度:"+binfmation.getLongitude(),  0 , font_size);
            //设置纬度
            g.drawString("纬度:"+binfmation.getLatitude(),  0 , font_size*2);
            //设置地址
            String address="地址:"+binfmation.getAddress();
            int address_size=getTextLength(address)*font_size;
            if(address_size<buffImg.getWidth()) {
                g.drawString(address,  0 , font_size*(3));
            }else {
                for (int i = 0; i <=address_size/buffImg.getWidth(); i++) {
                    if(i==0) {
                        g.drawString(address.substring( 0,buffImg.getWidth()/font_size*(i+1)),  0 , font_size*(2+i+1));
                    }else {
                        if(i==address_size/buffImg.getWidth()) {
                            g.drawString(address.substring( buffImg.getWidth()/font_size*(i),(address.length()) ), 0 , font_size*(5+i+1));
                        }else{
                            g.drawString(address.substring( buffImg.getWidth()/font_size*(i),buffImg.getWidth()/font_size*(i+1) ), 0 , font_size*(5+i+1));
                        }
                        
                    }
                }
            }
            
            
            //设置时间
            g.drawString("时间:"+ DateUtil.sdf.format(new Date()),  0 , font_size*4);
            //设置机房id
            g.drawString("机房ID:"+binfmation.getStationId(),  0 , font_size*5);
            //设置备注
            String note="备注:"+binfmation.getStationName();
            int note_size=getTextLength(note)*font_size;
            //System.out.println(getTextLength(binfmation.getStationName()));
            //System.out.println("font_size:"+font_size+"   note_size:"+note_size+"  buffImg.getWidth():"+buffImg.getWidth());
            if(note_size<buffImg.getWidth()) {
                 g.drawString(note,  0 , font_size*6);
            }else {
                for (int i = 0; i <=note_size/buffImg.getWidth(); i++) {
                    if(i==0) {
                        g.drawString(note.substring( 0,buffImg.getWidth()/font_size*(i+1) ),  0 , font_size*(5+i+1));
                    }else {
                        if(i==note_size/buffImg.getWidth()) {
                            g.drawString(note.substring( buffImg.getWidth()/font_size*(i),(note.length()) ), 0 , font_size*(5+i+1));
                        }else{
                            g.drawString(note.substring( buffImg.getWidth()/font_size*(i),buffImg.getWidth()/font_size*(i+1) ), 0 , font_size*(5+i+1));
                        }
                        
                    }
                }
            }
            
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(newImagePath);
           //System.out.println(os);
           ImageIO.write(buffImg, "JPG", os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           /* try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    }
    //计算水印文本长度
    //1、中文长度即文本长度 2、英文长度为文本长度二分之一
    public static int getTextLength(String text){
        //水印文字长度
        int length = text.length();
 
        for (int i = 0; i < text.length(); i++) {
            String s =String.valueOf(text.charAt(i));
            if (s.getBytes().length>1) {
                length++;
            }
        }
        length = length%2==0?length/2:length/2+1;
        return length;
    }
    
 
    //读取文件(图片)长,宽,图片名字
    public static ImageSize ImageInfor(File file) {
        ImageSize ims=new ImageSize();
        java.awt.Image srcImg;
        try {
            srcImg = ImageIO.read(file);
            ims.setHight(srcImg.getHeight(null));//文件的高
            ims.setWidth(srcImg.getWidth(null));//文件的宽
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ims;
    }
    
    /**
     *    读取所有上传过图片和视频的机房id文件夹
     * @return
     */
    @GetMapping("readAllStation")
    @ApiOperation(notes = "",value="读取所有上传过图片和视频的机房id文件夹")
    public ServiceModel ReadAllStation() {
        String fileRoot = "stationsrc";
        ServiceModel model = new ServiceModel();    
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();                                                    //获取服务器所在的绝对路径
        String root = str+"/"+fileRoot+"/";                                                                                    // 上传路径
        File files = new File(root);
        File[] sourses = files.listFiles();
        List<File> allfiles = new ArrayList<File>();
        for (int i = 0; i < sourses.length; i++) {
            if(sourses[i].isDirectory()) {
                allfiles.add(sourses[i]);
            }
        }
        if(allfiles.size()>0) {
            model.setCode(1);
            model.setData(allfiles);
        }else {
            model.setCode(0);
            model.setMsg("暂无机房资源");
        }
 
        return model;
    }
    
    /**
     *     删除指定的资源文件
     * @return
     */
    @DeleteMapping("file")
    @ApiOperation(notes = "",value="删除指定的资源文件")
    public ServiceModel deleteFile(@RequestBody MyFile myFile) {
        ServiceModel model = new ServiceModel();
        // MyFile myfile = getGson().fromJson(json, MyFile.class);
        List listU=new ArrayList();//存放操作记录
        String fileRoot = "stationsrc";
        String loadpath = ActionUtil.getSession().getServletContext().getRealPath("/");
        String str = new File(loadpath).getParentFile().getAbsolutePath();                                                                //获取服务器所在的绝对路径
        String targetFilePath = str+"/"+fileRoot+"/"+myFile.getFilePath()+"/"+myFile.getFileType()+"/"+myFile.getFileName();            // 上传路径
        File file = new File(targetFilePath);
        //System.out.println(targetFilePath);
        if(file.exists() && file.isFile()) {
            try {
                file.delete();
                model.setCode(1);
                model.setMsg("删除成功");
            } catch (Exception e) {
                model.setMsg("删除失败");
                e.printStackTrace();
            }
            {
                String msg=((User_inf)ActionUtil.getUser()).getuName()+"删除"+myFile.getFilePath()+"机房的"+myFile.getFileName();
                User_log ulog=UinfDaoFactory.CreateULog(UinfDaoFactory.Delete, msg);
                listU.add(ulog);
                (new User_logService()).addPro(listU);//将用户的操作记录下来
             }
        }else {
            model.setMsg("文件不存在");
        }
 
        return model;
    }
 /*
    public static void main(String[] args) {
        *//*String filePath = "D:/test/a/a.txt";
        //ActionUtil.createFileRootIFNotExist(filePath);
        
        File file = new File(filePath);
        System.out.println(ActionUtil.tojson(file));*//*
        //GraphicsFile("我是鲁星伟","D:\\1.jpg","D:\\2.jpg",0,new Color(255,0,0),"JPG");
        BattMap_information binfmation=new BattMap_information();
        binfmation.setStationId("42000001");
        binfmation.setStationName("广西省-百色-GX百色乐业县立新小区WF-BTS设备");
        binfmation.setAddress("百色市乐业县立新小区附近居民楼上");
        binfmation.setLongitude(106.55);
        binfmation.setLatitude(24.78);
        File file=new File("D:\\1.jpg");
        String filePath = "D:\\2.jpg";
        //String filename="2.jpg";
        GraphicsFile(binfmation,file,filePath);
    }*/
}