action中实现对批量文件上传的封装

     如今,文件(尤其是图片)上传,在前后台的应用相当普遍,上传头像、共享资料等已成为最基本应用。我们很希望通过一个万能的封装方法来实现一劳永逸的效果。

    接下来,就来为大家介绍具体实现。

    首先,我们需要一个struts框架下的项目工程,在webRoot目录下新建upload文件夹,用来存放上传文件

    然后,写一个简单的jsp,实现(批量)文件上传功能,这里注意:将所有上传文件框的name属性设为file,以便action接收

    之后,编写action,在action内首先要写入如下几个变量,及其get/set方法。

        private List<File> file;
        private List<String> fileFileName;
	private List<String> fileContentType;

     各自代表的意义一目了然。

     接下来就正式编写封装方法


public String uploadImg() throws IOException {
		String str = null;
		// 得到工程保存图片的路径
		String root = ServletActionContext.getRequest().getRealPath("/upload");

		// 循环上传的文件
		for (int i = 0; i < file.size(); i++) {
			InputStream is = new FileInputStream(file.get(i));

			// 得到图片保存的位置(根据root来得到图片保存的路径在tomcat下的该工程里)
			File destFile = new File(root, this.getFileFileName().get(i));
			str = destFile.getName();
			// 把图片写入到上面设置的路径里
			OutputStream os = new FileOutputStream(destFile);
			byte[] buffer = new byte[400];
			int length = 0;
			while ((length = is.read(buffer)) > 0) {
				os.write(buffer, 0, length);
			}
			is.close();
			os.close();
		}

		return str;
	}

     OK,这个方法既实现了将文件保存到tomcat下的相应文件夹中,又将保存的文件名告诉了我们, "upload/" + uploadImg()   即是本工程下的路径。

     如果文件是某对象的一个属性,那么直接XXX.setXxx( "upload/" + uploadImg())  存于数据库


下一篇  介绍文件的转移  

           以前的文件上传只是存放于tomcat本项目下的文件夹中,接下来我们要实现本项目上传文件至其他项目的文件夹下,如商城后台如何将后台上架图片放到前台展示,欢迎关注


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 实现文件批量上传批量下载的步骤如下: 1. 引入相关依赖 在 pom.xml 文件添加以下依赖: ```xml <!-- 文件上传 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 文件下载 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2. 配置上传文件存储路径 在 application.properties 文件添加以下配置: ```properties # 上传文件存储路径 file.upload-dir=/path/to/upload/dir ``` 3. 实现文件上传 在控制器添加以下代码: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileController { // 上传文件存储路径 @Value("${file.upload-dir}") private String uploadDir; // 文件上传页面 @GetMapping("/upload") public String showUploadForm() { return "upload"; } // 处理文件上传请求 @PostMapping("/upload") public String handleFileUpload(@RequestParam("files") List<MultipartFile> files, Model model) { // 创建上传文件存储路径 Path uploadPath = Paths.get(uploadDir); if (!Files.exists(uploadPath)) { try { Files.createDirectories(uploadPath); } catch (IOException e) { throw new RuntimeException("Failed to create upload directory", e); } } // 上传文件并保存 List<String> fileNames = files.stream().map(file -> { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); Path filePath = uploadPath.resolve(fileName); try { Files.copy(file.getInputStream(), filePath); } catch (IOException e) { throw new RuntimeException("Failed to store file " + fileName, e); } return fileName; }).collect(Collectors.toList()); // 返回上传结果 model.addAttribute("message", "Uploaded files: " + fileNames); return "upload"; } } ``` 上面的代码,`showUploadForm` 方法返回文件上传页面,`handleFileUpload` 方法处理文件上传请求,将上传文件保存到指定路径。 上传界面的 HTML 代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <h1>文件上传</h1> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="files" multiple> <button type="submit">上传</button> </form> <div th:if="${message}"> <p th:text="${message}"></p> </div> </body> </html> ``` 4. 实现文件下载 在控制器添加以下代码: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileController { // 上传文件存储路径 @Value("${file.upload-dir}") private String uploadDir; // 文件上传页面 @GetMapping("/upload") public String showUploadForm() { return "upload"; } // 处理文件上传请求 @PostMapping("/upload") public String handleFileUpload(@RequestParam("files") List<MultipartFile> files, Model model) { // 创建上传文件存储路径 Path uploadPath = Paths.get(uploadDir); if (!Files.exists(uploadPath)) { try { Files.createDirectories(uploadPath); } catch (IOException e) { throw new RuntimeException("Failed to create upload directory", e); } } // 上传文件并保存 List<String> fileNames = files.stream().map(file -> { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); Path filePath = uploadPath.resolve(fileName); try { Files.copy(file.getInputStream(), filePath); } catch (IOException e) { throw new RuntimeException("Failed to store file " + fileName, e); } return fileName; }).collect(Collectors.toList()); // 返回上传结果 model.addAttribute("message", "Uploaded files: " + fileNames); return "upload"; } // 文件下载页面 @GetMapping("/download") public String showDownloadForm(Model model) throws IOException { // 获取上传文件列表 Path uploadPath = Paths.get(uploadDir); List<String> fileNames = Files.list(uploadPath) .filter(Files::isRegularFile) .map(Path::getFileName) .map(Path::toString) .collect(Collectors.toList()); model.addAttribute("fileNames", fileNames); return "download"; } // 处理文件下载请求 @GetMapping("/download") public ResponseEntity<Resource> handleFileDownload(@RequestParam("fileName") String fileName) throws IOException { // 获取文件的字节数组 Path uploadPath = Paths.get(uploadDir); Path filePath = uploadPath.resolve(fileName); byte[] fileContent = Files.readAllBytes(filePath); // 创建文件资源 ByteArrayResource resource = new ByteArrayResource(fileContent); // 返回文件下载响应 return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(fileContent.length) .body(resource); } } ``` 上面的代码,`showDownloadForm` 方法返回文件下载页面,`handleFileDownload` 方法处理文件下载请求,将指定文件的字节数组封装成 `ByteArrayResource` 对象,并设置下载响应的头信息。 文件下载页面的 HTML 代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件下载</title> </head> <body> <h1>文件下载</h1> <ul> <li th:each="fileName : ${fileNames}"> <a th:href="@{/download(fileName=${fileName})}" th:text="${fileName}"></a> </li> </ul> </body> </html> ``` 上面的代码,使用了 Thymeleaf 模板引擎,动态生成文件下载链接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值