cy
2022-06-21 129904537f66509f97b285e7eb4f42b3dc349dd0
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
package cn.ksource.core.util;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
public class FileUtil {
    
    public static void main(String[] args) {
        System.out.println(FileUtil.getFileDirectory("c:\\23123\\23124214.txt"));
        System.out.println(FileUtil.rename("c:\\23123\\yangkai.txt", StringUtil.getUUID()));
        System.out.println(FileUtil.renameWithPath("c:\\23123\\yangkai.txt", StringUtil.getUUID()));
        
    }
    
    /**
     * 功能描述:删除单个文件<BR>
     * 
     * @param file
     * @author:杨凯<BR>
     *            时间:Apr 16, 2009 1:55:11 PM<BR>
     */
    public static void deleteFile(File file) {
        file.delete();
    }
    
    public static String getFileExtendName(String path){
        return StringUtils.right(path, path.length() - path.lastIndexOf(".")-1);
    }
    
    /**
     * 文件重命名
     * @param oldName 旧文件名称,包含扩展名
     * @param newName 新文件名称,不需要包含扩展名
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Dec 9, 2013 7:11:17 PM
     */
    public static String rename(String oldName,String newName){
        String extendName = getFileExtendName(oldName);
        if (StringUtils.isNotBlank(extendName)) {
            return newName + "." + extendName;
        }
        return newName;
    }
    
    /**
     * 带有路径的文件重命名
     * @param filePath 文件路径
     * @param newName 新文件名称,不需要扩展名
     * @return
     * @version V1.0.0
     * @author 杨凯
     * @date Dec 10, 2013 8:56:59 AM
     */
    public static String renameWithPath(String filePath,String newName){
        String extendName = getFileExtendName(filePath);
        if (StringUtils.isNotBlank(extendName)) {
            return getFileDirectory(filePath) + File.separator + newName + "." + extendName;
        } 
        return getFileDirectory(filePath) + File.separator + newName;
    }
    
    
    
    public static String getFileDirectory(String path){
        return new File(path).getParent();
    }
 
    /**
     * 功能描述:删除目录,并删除该目录下的所有文件<BR>
     * 
     * @param dir
     * @return
     * @author:杨凯<BR>
     *            时间:Apr 16, 2009 1:55:21 PM<BR>
     */
    public static boolean deleteDirectory(File dir) {
        if ((dir == null) || !dir.isDirectory()) {
            throw new RuntimeException("要删除的目录不存在,或者不是目录");
        }
 
        
        File[] files = dir.listFiles();
        int sz = files.length;
 
        for (int i = 0; i < sz; i++) {
            if (files[i].isDirectory()) {
                if (!deleteDirectory(files[i])) {
                    return false;
                }
            } else {
                if (!files[i].delete()) {
                    return false;
                }
            }
        }
 
        if (!dir.delete()) {
            return false;
        }
        return true;
    }
    
    
    /**
     * description: Copy file<br>
     * 
     * @param src
     * @param target
     * @throws IOException
     *             Mar 27, 2010
     * @author huxiao kskr@qq.com
     */
    public static void copyFile(String src, String target) throws IOException {
        FileInputStream in = new FileInputStream(src);
        File file = new File(target);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
 
        FileOutputStream out = new FileOutputStream(file);
        int c;
        byte buffer[] = new byte[1024];
        while ((c = in.read(buffer)) != -1) {
            for (int i = 0; i < c; i++)
                out.write(buffer[i]);
        }
        in.close();
        out.close();
    }
 
    /*
     * private static BufferedImage resize(BufferedImage source, int targetW,
     * int targetH) { // targetW,targetH分别表示目标长和宽 int type = source.getType();
     * BufferedImage target = null; double sx = (double) targetW /
     * source.getWidth(); double sy = (double) targetH / source.getHeight(); //
     * 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放 // 则将下面的if else语句注释即可 // if (sx >
     * sy) { // sx = sy; // targetW = (int) (sx * source.getWidth()); // } else { //
     * sy = sx; // targetH = (int) (sy * source.getHeight()); // } if (type ==
     * BufferedImage.TYPE_CUSTOM) { // handmade ColorModel cm =
     * source.getColorModel(); WritableRaster raster =
     * cm.createCompatibleWritableRaster(targetW, targetH); boolean
     * alphaPremultiplied = cm.isAlphaPremultiplied(); target = new
     * BufferedImage(cm, raster, alphaPremultiplied, null); } else target = new
     * BufferedImage(targetW, targetH, type); Graphics2D g =
     * target.createGraphics(); // smoother than exlax:
     * g.setRenderingHint(RenderingHints.KEY_RENDERING,
     * RenderingHints.VALUE_RENDER_QUALITY); g.drawRenderedImage(source,
     * AffineTransform.getScaleInstance(sx, sy)); g.dispose(); return target; }
     */
    /**
     * 功能描述:生成缩略图,并保留原图,新图片以:原图片名_宽_高.图片格式 保存<BR>
     * 
     * @param fromFile
     *            原file
     * @param width
     * @param hight
     * @author:杨凯<BR>
     *            时间:Apr 16, 2009 1:57:11 PM<BR>
     */
    public static String resizeImg(File fromFile, int width, int height) {
        return resizeImgForEqual(fromFile, width, height, false);
    }
 
    public static String resizeImgForEqual(File fromFile, int width, int height, boolean equal) {
        String newFileName = null;
        try {
            String name = fromFile.getName();
            String imgType = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
 
            String path = fromFile.getPath();
            String target = path.substring(0, path.lastIndexOf(".")) + "_" + width + "_" + height + "." + imgType;
            new ScaleImage().saveImageAsJpg(fromFile.getPath(), target, width, height, equal);
            newFileName = name.substring(0,name.lastIndexOf("."))+  "_" + width + "_" + height + "." + imgType;
        } catch (Exception e) {
            throw new RuntimeException("生成缩略图时发生错误!");
        }
        return newFileName;
    }
 
    /**
     * 功能描述:强制生成的缩略图的长宽等与提供的长宽<BR>
     * 
     * @param fromFile
     * @param width
     * @param height
     * @param equal
     * @author:杨凯<BR>
     *            时间:Sep 11, 2009 7:40:25 PM<BR>
     */
    public static void resizeForEqual(File fromFile, int width, int height, boolean equal) {
        try {
            new ScaleImage().saveImageAsJpg(fromFile.getPath(), fromFile.getPath(), width, height, equal);
        } catch (Exception e) {
            throw new RuntimeException("生成缩略图时发生错误!");
        }
    }
 
    /**
     * 功能描述:强制生成的缩略图的长宽等与提供的长宽 新图片以:原图片名_宽_高.图片格式 保留原图<BR>
     * 
     * @param fromFile
     * @param width
     * @param height
     * @param equal
     * @author:杨凯<BR>
     *            时间:Sep 11, 2009 7:40:25 PM<BR>
     */
    public static String resizeForEqualImg(File fromFile, int width, int height, boolean equal) {
        String newFileName = null;
        try {
            String name = fromFile.getName();
            String imgType = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
 
            String path = fromFile.getPath();
            String target = path.substring(0, path.lastIndexOf(".")) + "_" + width + "_" + height + "." + imgType;
            new ScaleImage().saveImageAsJpg(fromFile.getPath(), target, width, height, equal);
            newFileName = name.substring(0,name.lastIndexOf("."))+  "_" + width + "_" + height + "." + imgType;
        } catch (Exception e) {
            throw new RuntimeException("生成缩略图时发生错误!");
        }
        return newFileName;
    }
 
    /**
     * 功能描述:生成缩略图,用生成后的缩略图替代原图<BR>
     * 
     * @param fromFile
     *            原file
     * @param width
     * @param hight
     * @author:杨凯<BR>
     *            时间:Apr 16, 2009 1:57:11 PM<BR>
     */
    public static void resize(File fromFile, int width, int height) {
        resizeForEqual(fromFile, width, height, false);
    }
 
    /**
     * 功能描述:根据传入的路径,取得该路径的缩略图<BR>
     * 
     * @param path
     * @param width
     * @param height
     * @return
     * @author:杨凯<BR>
     *            时间:Apr 16, 2009 2:24:03 PM<BR>
     */
    public static String getImg(String path, int width, int height) {
        if (StringUtils.isBlank(path)) {
            return null;
        }
        String[] splitPath = path.split("\\.");
        String result = splitPath[0] + "_" + width + "_" + height + "." + splitPath[1].toLowerCase();
        return result;
    }
    
 
    /**
     * 功能描述:读取文件内容<BR>
     * 
     * @param file
     * @param encoding
     *            html文件使用gbk编码,此处使用utf-8编码,不会出现乱码
     * @return
     * @author:杨凯<BR>
     *            时间:Apr 30, 2009 5:49:37 PM<BR>
     */
    public static String file2String(File file, String encoding) {
        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();
        try {
            if (encoding == null || "".equals(encoding.trim())) {
                reader = new InputStreamReader(new FileInputStream(file), encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(file));
            }
            // 将输入流写入输出流
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        // 返回转换结果
        if (writer != null)
            return writer.toString();
        else
            return null;
    }
    
    public static void uploadFileWithFullPath(HttpServletRequest request,String fullPath,String[] allowTypes){
        //文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath(fullPath);
        //定义允许上传的文件扩展名
        String[] fileTypes = allowTypes;
        //最大文件大小
        long maxSize = 1000000;
        
        if(!ServletFileUpload.isMultipartContent(request)){
            throw new RuntimeException("没有可供上传的文件");
        }
        //检查目录
        File uploadDir = new File(savePath).getParentFile();
        if(!uploadDir.isDirectory()){
            throw new RuntimeException("目录不存在");
        }
        //检查目录写权限
        if(!uploadDir.canWrite()){
            throw new RuntimeException("目录没有写权限");
        }
 
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = null;
        try {
            items =upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator itr = items.iterator();
        String newFileName = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //检查文件大小
                if(item.getSize() > maxSize){
                    throw new RuntimeException("上传文件超过最大限制,最大100M");
                }
                if (fileTypes != null) {
                    //检查扩展名
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    if(!Arrays.<String>asList(fileTypes).contains(fileExt.toLowerCase())){
                        throw new RuntimeException("文件类型不允许上传");
                    }
                }
                try{
                    File uploadedFile = new File(savePath);
                    item.write(uploadedFile);
                }catch(Exception e){
                    e.printStackTrace();
                    throw new RuntimeException("文件上传失败");
                }
            }
        }
    }
 
    public static String uploadFile(HttpServletRequest request,String path,String[] allowTypes){
        //文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath("/")+ path + "/";
        //定义允许上传的文件扩展名
        String[] fileTypes = allowTypes;
        //最大文件大小
        long maxSize = 1000000;
        
        if(!ServletFileUpload.isMultipartContent(request)){
            throw new RuntimeException("没有可供上传的文件");
        }
        //检查目录
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory()){
            throw new RuntimeException("目录不存在");
        }
        //检查目录写权限
        if(!uploadDir.canWrite()){
            throw new RuntimeException("目录没有写权限");
        }
 
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        List items = null;
        try {
            items =upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator itr = items.iterator();
        String newFileName = null;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            long fileSize = item.getSize();
            if (!item.isFormField()) {
                //检查文件大小
                if(item.getSize() > maxSize){
                    throw new RuntimeException("上传文件超过最大限制,最大100M");
                }
                //检查扩展名
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                if(!Arrays.<String>asList(fileTypes).contains(fileExt.toLowerCase())){
                    throw new RuntimeException("文件类型不允许上传");
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try{
                    File uploadedFile = new File(savePath, newFileName);
                    item.write(uploadedFile);
                }catch(Exception e){
                    throw new RuntimeException("文件上传失败");
                }
            }
        }
        return newFileName;
    }
    
    
    /**
     * SpringMVC 单文件上传
     * @param request HttpServletRequest对象 <br/>
     * @param formFieldName 表单中file组件的name,如:<input type="file" name="xxx" /> <br/>
     * @param path 服务器端保存的路径,相对于ROOT的路径如:/userfile/images/ <br/>
     * @param allowTypes 运行上传的文件类型,数组,请用小写标识 <br/>
     * @return 文件路径 /userfile/images/20130912134523_134.png
     * @version V1.0.0
     * @author 杨凯
     * @date Dec 16, 2013 12:04:54 PM
     */
    public static String uploadFile4SpringMVC(HttpServletRequest request,String formFieldName,String path,String[] allowTypes)  throws MyFileUploadException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
        //文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath(path) + File.separator;
        //定义允许上传的文件扩展名
        String[] fileTypes = allowTypes;
        
        MultipartFile multipartFile = multipartRequest.getFile(formFieldName);
        
        
        return _uploadFile(path, savePath, fileTypes, multipartFile);
    }
    
    
    /**
     * SpringMVC 批量文件上传
     * @param request HttpServletRequest对象 <br/>
     * @param formFieldName 表单中file组件的name,如:<input type="file" name="xxx" /> <br/>
     * @param path 服务器端保存的路径,相对于ROOT的路径如:/userfile/images/ <br/>
     * @param allowTypes 运行上传的文件类型,数组,请用小写标识 <br/>
     * @return 文件路径<fieldName,serverFieldPath> /userfile/images/20130912134523_134.png
     * @version V1.0.0
     * @author 杨凯
     * @date Dec 16, 2013 12:04:54 PM
     */
    public static Map<String,String> uploadFile4SpringMVC(HttpServletRequest request,String path,String[] allowTypes)  throws MyFileUploadException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
        //文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath(path) + File.separator;
        //定义允许上传的文件扩展名
        String[] fileTypes = allowTypes;
        
        
        Iterator<String> fileNameIterator =  multipartRequest.getFileNames();
        
        Map<String,String> map = new HashMap<String,String>();
        
        for (Iterator<String> iterator = fileNameIterator; iterator.hasNext();) {
            String name = iterator.next();
            MultipartFile multipartFile = multipartRequest.getFile(name);
            String serverPath = _uploadFile(path, savePath, fileTypes, multipartFile);
            if (StringUtils.isNotBlank(serverPath)) {
                map.put(name, serverPath);
            }
        }
        
        return map;
    }
 
 
    /**
     * SpringMVC 批量文件上传
     * @param request HttpServletRequest对象 <br/>
     * @param path 服务器端保存的路径,相对于ROOT的路径如:/userfile/images/ <br/>
     * @param allowTypes 运行上传的文件类型,数组,请用小写标识 <br/>
     * @return Map<文件名称,文件保存路径>
     * @version V1.0.0
     * @author zxl
     * @date Dec 16, 2013 12:04:54 PM
     */
    public static List<FileInfo> uploadFiles(HttpServletRequest request,String path,String[] allowTypes)  throws MyFileUploadException {
        List<FileInfo> infos = new ArrayList<FileInfo>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath(path) + File.separator;
        //定义允许上传的文件扩展名
        String[] fileTypes = allowTypes;
        Iterator<String> fileNameIterator =  multipartRequest.getFileNames();
        Map<String,String> map = new HashMap<String,String>();
 
        for (Iterator<String> iterator = fileNameIterator; iterator.hasNext();) {
            String name = iterator.next();
            List<MultipartFile> multipartFiles = multipartRequest.getFiles(name);
            for(MultipartFile multipartFile:multipartFiles){
                FileInfo info = new FileInfo();
                String fileName = multipartFile.getOriginalFilename();
                String serverPath = _uploadFile(path, savePath, fileTypes, multipartFile);
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                info.setFieldName(name);
                info.setExtName(fileExt);
                info.setFileSize(String.valueOf(multipartFile.getSize()));
                info.setOriginalFilename(fileName);
                if (StringUtils.isNotBlank(serverPath)) {
                    info.setFilePath(serverPath);
                }
                infos.add(info);
            }
        }
        return infos;
    }
    public static class FileInfo{
        private String fieldName;
        private String originalFilename;
        private String extName;
        private String  fileSize;
        private String filePath;
 
        public String getFilePath() {
            return filePath;
        }
 
        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }
 
        public String getFieldName() {
            return fieldName;
        }
 
        public void setFieldName(String fieldName) {
            this.fieldName = fieldName;
        }
 
        public String getOriginalFilename() {
            return originalFilename;
        }
 
        public void setOriginalFilename(String originalFilename) {
            this.originalFilename = originalFilename;
        }
 
        public String getExtName() {
            return extName;
        }
 
        public void setExtName(String extName) {
            this.extName = extName;
        }
 
        public String getFileSize() {
            return fileSize;
        }
 
        public void setFileSize(String fileSize) {
            this.fileSize = fileSize;
        }
    }
    
    
    
 
    private static String _uploadFile(String path, String savePath, String[] fileTypes, MultipartFile multipartFile) throws MyFileUploadException {
        
        //最大文件大小
        long maxSize = 100 * 1024 * 1024;
        
        if(multipartFile == null || multipartFile.isEmpty()){
            return null;
        }
        
        String fileName = multipartFile.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if(fileTypes!=null){
            //检查扩展名
            if(!Arrays.<String>asList(fileTypes).contains(fileExt.toLowerCase())){
                throw new MyFileUploadException("文件类型:"+ fileExt +" 不允许上传,只允许格式:" + Arrays.<String>asList(fileTypes).toString());
            }
        }
        if (maxSize < multipartFile.getSize()) {
            throw new MyFileUploadException("文件超出最大文件上传限制:100M,实际上传文件:" + multipartFile.getSize()/1024/1024 + "M");
        }
        
        
        //检查目录
        File uploadDir = new File(savePath);
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        
        //检查目录写权限
        if(!uploadDir.canWrite()){
            throw new MyFileUploadException("目录没有写权限");
        }
        
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt;
        
        String newFilePath = savePath + newFileName;
        
        try {
            FileUtils.writeByteArrayToFile(new File(newFilePath), multipartFile.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyFileUploadException("上传文件失败:"+e.getMessage());
        }
        
        if (path.endsWith("/")) {
            return path + newFileName;
        } else {
            return path + "/" + newFileName;
        }
    }
    
    
    
    /**
     * SpringMVC 单文件上传(返回名称和路径)
     * @param request HttpServletRequest对象 <br/>
     * @param formFieldName 表单中file组件的name,如:<input type="file" name="xxx" /> <br/>
     * @param path 服务器端保存的路径,相对于ROOT的路径如:/userfile/images/ <br/>
     * @param allowTypes 运行上传的文件类型,数组,请用小写标识 <br/>
     * @return 文件路径 /userfile/images/20130912134523_134.png
     * @version V1.0.0
     * @author 杨凯
     * @date Dec 16, 2013 12:04:54 PM
     */
    public static Map<String,String> uploadFile4SpringMVCMap(HttpServletRequest request,String formFieldName,String path,String[] allowTypes)  throws MyFileUploadException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
        //文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath(path) + File.separator;
        //定义允许上传的文件扩展名
        String[] fileTypes = allowTypes;
        
        MultipartFile multipartFile = multipartRequest.getFile(formFieldName);
        String fileName = multipartFile.getOriginalFilename();
        
        String upPath =  _uploadFile(path, savePath, fileTypes, multipartFile);
        
        
        Map map = new HashMap();
        map.put("path", upPath);
        map.put("fileName", fileName);
        return map;
    }
}