springboot 上传附件功能【本站点】和【远程站点】
上传附件
1.1 静态页面 目录:src\main\resources\static\UploadFile.html ,请求地址:http://localhost:8081/UploadFile.html
1.2 静态页面内容 修改: ajax-url 可以测试1、本站点存储,2、远程站点存储
// 1、 本站点:ocalReceiveUpload.do 2、远程站点存储:fileUpload.do
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传附件</title> <style> .progress { width: 200px; height: 10px; border: 1px solid #ccc; border-radius: 10px; margin: 10px 0px; overflow: hidden; } /* 初始状态设置进度条宽度为0px */ .progress > div { width: 0px; height: 100%; background-color: yellowgreen; transition: all .3s ease; } </style> <script type="text/javascript" src="/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function (){ }); $(function(){ $("#uploadFile").click(function(){ // 获取要上传的文件 var photoFile =$("#photo")[0].files[0] if(photoFile==undefined){ alert("您还未选中文件") return; } // 将文件装入FormData对象 var formData =new FormData(); formData.append("headPhoto",photoFile) // ajax向后台发送文件 $.ajax({ type:"post", data:formData, url:"localReceiveUpload.do", // 1、 本站点action:ocalReceiveUpload.do 2、远程站点存储:fileUpload.do processData:false, contentType:false, success:function(result){ // 接收后台响应的信息 alert(result.message) // 图片回显 // $("#headImg").attr("src","http://192.168.3.4:8080/upload/"+result.newFileName); // 图片回显 $("#headImg").attr("src","upload/"+result.newFileName); }, xhr: function() { var xhr = new XMLHttpRequest(); //使用XMLHttpRequest.upload监听上传过程,注册progress事件,打印回调函数中的event事件 xhr.upload.addEventListener('progress', function (e) { //loaded代表上传了多少 //total代表总数为多少 var progressRate = (e.loaded / e.total) * 100 + '%'; //通过设置进度条的宽度达到效果 $('.progress > div').css('width', progressRate); }) return xhr; } }) }) }) </script> </head> <body> <form action="addPlayer" method="get"> <p>头像: <br/> <input id="photo" type="file"> <%--图片回显--%> <br/> <img id="headImg" style="width: 200px;height: 200px" alt="你还未上传图片"> <br/> <%--进度条--%> <div class="progress"> <div></div> </div> <a id="uploadFile" href="javascript:void(0)">立即上传</a> </p> </form> </body> </html>
1.3服务器Java代码
@RestController public class UploadFile { // 文件存储位置 private final static String FILESERVER="http://192.168.3.4:8080/upload/"; /** 001 * 远程服务器文件存储 * @param headPhoto * @param req * @return * @throws Exception */ @RequestMapping(value = "fileUpload.do",method = {RequestMethod.POST,RequestMethod.GET}) public Map<String,String> receiveUpload(MultipartFile headPhoto, HttpServletRequest req) throws Exception{ Map<String,String> map=new HashMap<>(); // 获取文件名 String originalFilename = headPhoto.getOriginalFilename(); // 避免文件名冲突,使用UUID替换文件名 String uuid = UUID.randomUUID().toString(); // 获取拓展名 String extendsName = originalFilename.substring(originalFilename.lastIndexOf(".")); // 新的文件名 String newFileName=uuid.concat(extendsName); // 创建 sun公司提供的jersey包中的client对象 Client client=Client.create(); WebResource resource = client.resource(FILESERVER + newFileName); // 文件保存到另一个服务器上去了 resource.put(String.class, headPhoto.getBytes()); // 上传成功之后,把文件的名字和文件的类型返回给浏览器 map.put("message", "上传成功"); map.put("newFileName",newFileName); map.put("filetype", headPhoto.getContentType()); return map; } /** 002 * 本站点文件 存储 * @param headPhoto * @param req * @return * @throws Exception */ @RequestMapping(value = "localReceiveUpload.do",method = {RequestMethod.POST,RequestMethod.GET}) public Map<String,String> localReceiveUpload(MultipartFile headPhoto, HttpServletRequest req) throws Exception{ Map<String,String> map=new HashMap<>(); // 控制文件大小 if(headPhoto.getSize()>1024*1024*5){ map.put("message", "文件大小不能超过5M"); return map; } String filePath1=req.getContextPath(); System.out.println("filePath1 = " + filePath1); String filePath02=req.getServletPath(); System.out.println("filePath02 = " + filePath02); // 获取要上传的目录 ***1、【需配置 idea 环境变量:\multiplethread\src\main\resources】 // 2、 filePath 可以指定绝对路径 以便于呈现时方便 String filePath=req.getServletContext().getRealPath("/upLoad"); String realPath = req.getServletContext().getRealPath("/upload"); File fileBasePath=new File(filePath); if(!fileBasePath.exists()){ fileBasePath.mkdir(); } // 获取文件名 String originalFilename = headPhoto.getOriginalFilename(); // 避免文件名冲突,使用UUID替换文件名 String uuid = UUID.randomUUID().toString(); // 获取拓展名 String extendsName = originalFilename.substring(originalFilename.lastIndexOf(".")); // 新的文件名 String newFileName=uuid.concat(extendsName); // 文件存储位置 File file =new File(fileBasePath,newFileName); // 文件保存 headPhoto.transferTo(file); // 上传成功之后,把文件的名字和文件的类型返回给浏览器 map.put("message", "上传成功"); map.put("newFileName",newFileName); map.put("filetype", headPhoto.getContentType()); return map; } }
1.4 所需pom节点
<!-- 用于远程上传文件-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
1.5 当测试远程方件存储时需要配置远程 tomcat 站点存储文件,需要部署一个单独tomcat站点做为文件服务站点
1.5.1 server.xml设置远程服务器端口号 需要关注
<Server port="8005" shutdown="SHUTDOWN">
和
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
1.5.2 web.xml需要设置 新加节点
<init-param> <param-name>readonly</param-name> <param-value>false</param-value> </init-param>
远程服务器中设置非只读
1.5.3 webapps下创建一个upload目录
lcoalhost:xxxx 测试新部署的tomcat 是否成功
ps:springboot自定义资源映射
https://blog.csdn.net/qq_44196212/article/details/124242026?spm=1001.2014.3001.5502
1.5.6 resource 目录下文件下载 download
spring boot 中使用
下载目录表示: String resourceName = "classpath:Attachment/dmall_open_demo.zip";
@Autowired private ResourceLoader resourceLoader; @GetMapping("/download") public ResponseEntity<InputStreamResource> download() throws IOException { String resourceName = "classpath:Attachment/dmall_open_demo.zip"; Resource resource = resourceLoader.getResource(resourceName); InputStreamResource inputStreamResource = new InputStreamResource(resource.getInputStream()); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=dmall_open_demo.zip"); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); return ResponseEntity.ok() .headers(headers) .body(inputStreamResource); }
1.5.7
绝对路径读取文件
1 2 3 | String pathTxt= "D:\\WorkAll\\OtherProject\\otherPart\\open-demo2\\src\\main\\resources\\images\\txt02.txt" ; byte [] encoded = Files.readAllBytes(Paths.get(pathTxt)); |
1.5.8 不打开页面直接下载 通过controller
@GetMapping("/download") @ResponseBody public ResponseEntity<InputStreamResource> download(Long venderId) throws IOException { log.info("开始下载"); LoginContext context = LoginContext.getHolder().get(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=dmall-open-sdk-2.0.0.jar"); InputStream inputStream = sdkService.getJarDataNew(context==null?null:context.getUserId(), context==null?venderId:null,2); return ResponseEntity .ok() .headers(headers) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(new InputStreamResource(inputStream)); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构