SpringMVC之 文件上传和下载

ops/2024/10/22 13:28:24/

1. 文件上传

1.1 前端注意事项

        文件上传操作,前端的表单项需要如下三项设置:

        (1)input标签的type属性应设置为file,并且注意不要在input标签中设置value属性,因为这可能导致文件上传不成功;
        (2)请求方式为 method="post" ;

        (3)enctype="multipart/form-data"。

1.2 后端注意事项

        文件上传操作,后端需要注意:

        (1)可以在项目的配置文件 application.properties或application.yml中设置文件大小限制,以避免上传过大的文件导致服务器资源耗尽,例如:

        (2)后端需要写一个处理上传文件的处理器,把接收到的文件保存到服务器指定目录下等其他操作。

1.3 前后端完整示例程序

1.3.1 前端

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head><meta charset="UTF-8"><title>文件上传和下载</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">用户名:<input type="text" name="username"/><br/>头 像 :<input type="file" name="headerImg" /><br/>生活照:<input type="file" name="lifeImages" multiple></br><input type="submit" value="提交"/>
</form>
</body>
</html>

1.3.2 后端

package com.shg.springmvc.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.nio.file.Paths;@Controller
public class PageTestController {@RequestMapping(value = "/file/upload", method = RequestMethod.POST)@ResponseBodypublic String fileUpload(@RequestParam(value = "headerImg") MultipartFile file,@RequestParam(value = "lifeImages") MultipartFile[] lifeImages,@RequestParam(value = "username") String userName) throws IOException {System.out.println("用户名:" + userName);System.out.println("头像 - 文件名称:" + file.getOriginalFilename());file.transferTo(Paths.get("D:\\tempPic\\" + file.getOriginalFilename()));for (MultipartFile lifeImage : lifeImages) {System.out.println("生活照 - 文件名称:" + lifeImage.getOriginalFilename());lifeImage.transferTo(Paths.get("D:\\tempPic\\" + file.getOriginalFilename()));}return "success";}
}

2. 文件下载

        文件下载的写法比较固定,代码如下:

package com.shg.springmvc.controller;import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;@RestController
public class ResponseTestController {/*** 问题一:如果文件名称中包含中文,那么浏览器会乱码* 问题二:如果下载的文件比较大,会oom(内存溢出)** @return* @throws IOException*/@RequestMapping(value = "/download", method = RequestMethod.GET)public ResponseEntity<InputStreamResource> response_02() throws IOException {// 获取要下载的文件流String filePath = "D:\\tempPic\\生活照3.jpg";File file = new File(filePath);FileInputStream fileInputStream = new FileInputStream(file);// 解决问题一:使用URLEncoder.encode()方法对文件名称进行编码String fileName = URLEncoder.encode("你好啊.jpg", StandardCharsets.UTF_8);// 解决问题二:为了避免一次性读取文件过大,导致内存溢出,可以使用 InputStreamResource 来读取文件(将文件流包装成Resource对象)InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);return ResponseEntity.ok()// 设置响应头,告诉浏览器如何处理.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)// 下载文件的大小.contentLength(file.length())// 内容类型:流.contentType(MediaType.APPLICATION_OCTET_STREAM)// 响应体.body(inputStreamResource);}
}


http://www.ppmy.cn/ops/127578.html

相关文章

【Flutter】基础入门:代码基本结构

通过这个简单的 Flutter 示例程序&#xff0c;我们可以快速了解 Flutter 的代码结构&#xff0c;理解每个部分的作用。 import package:flutter/material.dart; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}…

初识git · 有关模型

目录 前言&#xff1a; 有关开发模型 前言&#xff1a; 其实文章更新到这里的时候&#xff0c;我们已经学习了可以满足我们日常生活中的基本需求的指令了&#xff0c;但是为什么要更新本篇文章呢&#xff1f;是因为实际生活中我们对于开发工作&#xff0c;运维工作&#xff…

提取图片内容的 Python 程序

&#x1f308;个人主页&#xff1a;易辰君-CSDN博客 &#x1f525; 系列专栏&#xff1a;https://blog.csdn.net/2401_86688088/category_12813012.html 目录 前言 一、安装依赖 二、下载安装chi_sim.traineddata文件 三、代码示例 前言 要编写一个提取图片内容的 Python …

标题:民峰金融科技:创新科技引领金融投资新时代

民峰金融科技凭借其领先的技术与专业的金融服务&#xff0c;正不断为全球投资者提供智能化的财富管理解决方案。依托大数据、人工智能等前沿科技&#xff0c;民峰金融科技帮助投资者实现资产增值与风险控制&#xff0c;成为全球金融科技领域的重要力量。 一、智能分析&#xf…

AlDente Pro for Mac电脑 充电限制保护工具 安装教程【简单,轻松上手】

Mac分享吧 文章目录 AlDente Pro for Mac 充电限制保护工具 安装完成&#xff0c;软件打开效果一、AlDente Pro for Mac 充电限制保护工具 Mac电脑版——v1.28.41️⃣&#xff1a;下载软件2️⃣&#xff1a;安装软件&#xff0c;将安装包从左侧拖入右侧文件夹中&#xff0c;等…

【分布式技术】中间件-zookeeper安装配置

文章目录 安装部署1. 安装ZooKeeper2. 配置ZooKeeper3. 启动ZooKeeper服务器4. 使用ZooKeeper命令行客户端5. 使用ZooKeeper的四个基本操作6. ZooKeeper集群模式7. 安全和权限8. 监控和日志 相关文献 安装部署 在Linux环境中操作ZooKeeper通常涉及以下几个方面&#xff1a; 1…

浙大数据结构:11-散列3 QQ帐户的申请与登陆

哈希表应用使用map&#xff0c;所以写起来并不难 1、主函数 感觉有点像map的简单应用&#xff0c;把所有条件都进行处理判断就行 #include <iostream> #include<string> #include<unordered_map> #include<algorithm> using namespace std; #define…

Lambda 表达式

Lambda 表达式是 C11 引入的一种匿名函数的方式&#xff0c;它允许你在需要函数的地方内联地定义函数&#xff0c;而无需单独命名函数 [capture clause](parameters) -> return_type {// 函数体 // 可以使用捕获列表中的变量 return expression; // 可选的返回语句 } 捕获…