Spring框架实现文件上传功能

网友投稿 302 2023-03-15


Spring框架实现文件上传功能

在java中实现文件的上传有多种方式,如smartUpload或是使用Strus2,本文与大家分享使用Spring框架中的MultipartFile类来实例文件的上传。

不啰嗦了,直接上干货。先是编写了一个实现文件上传的类FileUploadingUtil,此类中定义了两个对外公开的方法,upload和getFileMap。

前者需要传入一个Map参数,是用户提交的表单中的文件列表,最终返回值的也是一个Map类型对象,其键名为上传的文件名称,键值为文件在服务器上的存储路径;后者主要是用于测试用途,非主要功能,看官可以忽略此方法。

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 upload(Map files) throws IOException {

File file = new File(FILEDIR);

if (!file.exists()) {

file.mkdir();

}

Map result = new HashMap();

Iterator> 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) {

}http://

}

}

/**

* 遍历服务器目录,列举出目录中的所有文件(含子目录)

* @return

*/

public static Map getFileMap() {

logger.info(FileUploadingUtil.FILEDIR);

Map map = new HashMap();

File[] files = new File(FileUplhttp://oadingUtil.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类实现文件上传之功能。

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.emershttp://on.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 uploadedFiles = FileUploadingUtil.upload(mRequest.getFileMap());

Iterator> iter = uploadedFiles.entrySet().iterator();

while (iter.hasNext()) {

Entry 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类的错误。

依赖引用如下。

commons-fileupload

commons-fileupload

1.3.1


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java多线程同步器代码详解
下一篇:api接口文档模板是什么(api接口文档是干什么的)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~