激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring框架實現文件上傳功能

Spring框架實現文件上傳功能

2021-02-07 12:18chris_mao Java教程

這篇文章主要為大家詳細介紹了Spring框架實現文件上傳功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

在Java中實現文件的上傳有多種方式,如smartUpload或是使用Strus2,本文與大家分享使用Spring框架中的MultipartFile類來實例文件的上傳。

不啰嗦了,直接上干貨。先是編寫了一個實現文件上傳的類FileUploadingUtil,此類中定義了兩個對外公開的方法,upload和getFileMap。

前者需要傳入一個Map參數,是用戶提交的表單中的文件列表,最終返回值的也是一個Map類型對象,其鍵名為上傳的文件名稱,鍵值為文件在服務器上的存儲路徑;后者主要是用于測試用途,非主要功能,看官可以忽略此方法。

?
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
package com.emerson.cwms.utils;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
import org.springframework.web.multipart.MultipartFile;
 
/**
 * 文件上傳工具類
 *
 * @author Chris Mao(Zibing)
 *
 */
public class FileUploadingUtil {
 
  /**
   * 服務器上的保存路徑,在使用到上傳功能的Controller中對其進行賦值
   */
  public static String FILEDIR = null;
 
  /**
   * 上傳多個文件,返回文件名稱和服務器存儲路徑列表
   *
   * @param files
   * @return
   * @throws IOException
   */
  public static Map<String, String> upload(Map<String, MultipartFile> files) throws IOException {
    File file = new File(FILEDIR);
    if (!file.exists()) {
      file.mkdir();
    }
 
    Map<String, String> result = new HashMap<String, String>();
    Iterator<Entry<String, MultipartFile>> iter = files.entrySet().iterator();
    while (iter.hasNext()) {
      MultipartFile aFile = iter.next().getValue();
      if (aFile.getSize() != 0 && !"".equals(aFile.getName())) {
        result.put(aFile.getOriginalFilename(), uploadFile(aFile));
      }
    }
    return result;
  }
 
  /**
   * 上傳單個文件,并返回其在服務器中的存儲路徑
   *
   * @param aFile
   * @return
   * @throws FileNotFoundException
   * @throws IOException
   */
  private static String uploadFile(MultipartFile aFile) throws IOException {
    String filePath = initFilePath(aFile.getOriginalFilename());
    try {
      write(aFile.getInputStream(), new FileOutputStream(filePath));
    } catch (FileNotFoundException e) {
      logger.error("上傳的文件: " + aFile.getName() + " 不存在!!");
      e.printStackTrace();
    }
    return filePath;
  }
 
  /**
   * 寫入數據
   *
   * @param in
   * @param out
   * @throws IOException
   */
  private static void write(InputStream in, OutputStream out) throws IOException {
    try {
      byte[] buffer = new byte[1024];
      int bytesRead = -1;
      while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
      }
      out.flush();
    } finally {
      try {
        in.close();
        out.close();
      } catch (IOException ex) {
      }
    }
  }
 
  /**
   * 遍歷服務器目錄,列舉出目錄中的所有文件(含子目錄)
   * @return
   */
  public static Map<String, String> getFileMap() {
    logger.info(FileUploadingUtil.FILEDIR);
    Map<String, String> map = new HashMap<String, String>();
    File[] files = new File(FileUploadingUtil.FILEDIR).listFiles();
    if (files != null) {
      for (File file : files) {
        if (file.isDirectory()) {
          File[] files2 = file.listFiles();
          if (files2 != null) {
            for (File file2 : files2) {
              String name = file2.getName();
              logger.info(file2.getParentFile().getAbsolutePath());
              logger.info(file2.getAbsolutePath());
              map.put(file2.getParentFile().getName() + "/" + name,
                  name.substring(name.lastIndexOf("_") + 1));
            }
          }
        }
      }
    }
    return map;
  }
 
  /**
   * 返回文件存儲路徑,為防止重名文件被覆蓋,在文件名稱中增加了隨機數
   * @param name
   * @return
   */
  private static String initFilePath(String name) {
    String dir = getFileDir(name) + "";
    File file = new File(FILEDIR + dir);
    if (!file.exists()) {
      file.mkdir();
    }
    Long num = new Date().getTime();
    Double d = Math.random() * num;
    return (file.getPath() + "/" + num + d.longValue() + "_" + name).replaceAll(" ", "-");
  }
 
  /**
   *
   * @param name
   * @return
   */
  private static int getFileDir(String name) {
    return name.hashCode() & 0xf;
  }
}

Controller代碼,使用上述定義的FileUploadingUtil類實現文件上傳之功能。

?
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
package com.emerson.cwms.web; 
 
 
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
import com.emerson.cwms.utils.FileUploadingUtil;
 
/**
 * 文件上傳控制器
 *
 * @author Chris Mao(Zibing)
 *
 */
@Controller
@RequestMapping(value = "/files")
public class FileController {
   
  @RequestMapping(value = "/", method = RequestMethod.GET)
  public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
    iniFileDir(request);
     
    System.out.println(request.getAttribute("files"));
    model.addAttribute("files", FileUploadingUtil.getFileMap());
    return "files/list";
  }
   
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public String doUpload(HttpServletRequest request) {
    iniFileDir(request);
     
    try {
      MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
      Map<String, String> uploadedFiles = FileUploadingUtil.upload(mRequest.getFileMap());
 
      Iterator<Entry<String, String>> iter = uploadedFiles.entrySet().iterator();
      while (iter.hasNext()) {
        Entry<String, String> each = iter.next();
        System.out.print("Uploaded File Name = " + each.getKey());
        System.out.println(", Saved Path in Server = " + each.getValue());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "redirect:/files/";
  }
 
  private void iniFileDir(HttpServletRequest request) {
    FileUploadingUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "files/";
    if (FileUploadingUtil.FILEDIR == null) {
      FileUploadingUtil.FILEDIR = request.getSession().getServletContext().getRealPath("/") + "files/";
    }
  }
}

注意事項:一定要在pom.xml文件中添加對commons-fileupload的依賴引用,否則代碼在運行時會提示找不到FileItemFactory類的錯誤。

依賴引用如下。

?
1
2
3
4
5
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://blog.csdn.net/chris_mao/article/details/50321097

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 成人免费毛片在线观看 | 欧美日韩高清不卡 | 日本一级毛片在线播放 | 欧美成人精品不卡视频在线观看 | 免费在线观看中文字幕 | 国产亚洲欧美在线视频 | 久久国产精品99久久人人澡 | 亚州综合网| 91中文在线 | 亚洲电影免费观看国语版 | 中午字幕无线码一区2020 | 天天鲁在线视频免费观看 | 国产色视频在线观看免费 | asian超清日本肉体pics | 国产毛片aaa一区二区三区视频 | 国产成人视屏 | 毛片免费大全短视频 | 国产婷婷一区二区三区 | 国产91丝袜在线播放0 | 福利免费在线 | 农村寡妇偷毛片一级 | 国产免费一级淫片a级中文 99国产精品自拍 | 国产亚洲区 | 中文黄色一级片 | 欧美亚洲一区二区三区四区 | 欧洲狠狠鲁 | 亚洲最大中文字幕 | 本站只有精品 | 国产精品99久久久久久久女警 | 国内精品久久久久久久星辰影视 | 羞羞色院91精品网站 | 国产日本在线播放 | 一区二区精品在线 | 免费三级大片 | 中文字幕精品久久 | 成人h精品动漫一区二区三区 | 久久精品人人做人人爽 | 国产精品www | 91中文在线| 黄色网址入口 | 国产成人强伦免费视频网站 |