日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

spring boot基础教程之文件上传下载

發布時間:2024/9/30 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot基础教程之文件上传下载 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一文件上傳

文件上傳主要分以下幾個步驟:

(1)新建maven java project;
(2)在pom.xml加入相應依賴;
(3)新建一個文件上傳表單頁面;
(4)編寫controller;
(5)測試;
(6)對上傳的文件做一些限制;
(7)多文件上傳實現

好了,直接看代碼,代碼中有詳細注釋

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.wx</groupId><artifactId>springboot05</artifactId><version>0.0.1-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.2.RELEASE</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- jsp頁面支持 --><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency><!-- jstl標簽庫 --><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency></dependencies><build><finalName>${project.artifactId}</finalName><plugins><!-- java編譯插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.7</source><target>1.7</target><encoding>UTF-8</encoding></configuration></plugin><!-- 如果你不想用maven命令運行spring boot可以不用作此配置 --><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>

頁面文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="scheme" value="${pageContext.request.scheme}"></c:set> <c:set var="serverName" value="${pageContext.request.serverName}"></c:set> <c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set> <c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set> <c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${contextPath}/"></c:set><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="${basePath}"><title>文件上傳下載</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(e){$("[value=開始上傳]").click(function(e){var userName=$("[name=userName]").val();if(userName==""){window.alert("用戶名不為空");return;}var theFile=$("[name=theFile1]").val();if(theFile==""){window.alert("文件名不為空");return;}var theSubfix=theFile.substr(theFile.lastIndexOf('.')+1);theSubfix=theSubfix.toLowerCase();window.alert("ttt:"+theSubfix);var subfixs=["png","gif","jpg","jpeg","bmp"];var flag=false;for(var i=0;i<subfixs.length;i++){if(subfixs[i]==theSubfix){flag=true;break;}}if(!flag){window.alert("文件格式錯誤!");return;}$("[name=myFrm]").submit();}); }); </script> </head><body> <h1>文件上傳演示</h1> <form action="Upload.php" name="myFrm" method="post" enctype="multipart/form-data"><table border="1px"><tr><td>請輸入用戶名:</td><td><input type="text" name="userName"/></td></tr><!-- 第一個文件限定為圖片 --><tr><td>請選擇文件:</td><td><input type="file" name="theFile1"/></td></tr><tr><td>請選擇文件:</td><td><input type="file" name="theFile2"/></td></tr><tr><td colspan="2"><input type="button" value="開始上傳"/></td></tr></table> </form> </body> </html>

配置類

package com.wx.boot;import java.nio.charset.Charset;import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.boot.web.servlet.ErrorPage; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.http.converter.StringHttpMessageConverter;@Configuration @ComponentScan(basePackages = "com.wx.controler.*") public class SpringConfig {@Beanpublic StringHttpMessageConverter stringHttpMessageConverter() {StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));return converter;}//統一錯誤處理配置@Beanpublic EmbeddedServletContainerCustomizer containerCustomizer() {return new EmbeddedServletContainerCustomizer() {public void customize(ConfigurableEmbeddedServletContainer container) {//ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/Err404.html");ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/Err500.html");container.addErrorPages(error404Page,error500Page);}};} }

=啟動類=====

文件上傳控制器類

package com.wx.controler.user;import java.io.*; import java.util.*;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView;@Controller public class UploadController{@RequestMapping(value="/Upload.php",method=RequestMethod.POST)public ModelAndView login(HttpServletRequest request,HttpServletResponse response) throws Exception{String userName=request.getParameter("userName");HttpSession session=request.getSession();//獲得文件請求對象MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;String targetPath=session.getServletContext().getRealPath("/")+"uploads\\";System.out.println("path:"+targetPath+",userName:"+userName);File targetDir=new File(targetPath);if(!targetDir.exists()){targetDir.mkdirs();}//鍵是文件表單的名稱,值是文件對象Map<String, MultipartFile> fileMap = mRequest.getFileMap();Set<String> keys=fileMap.keySet();FileOutputStream fos=null;String srcName="";List<String> nameList=new ArrayList<String>();//對上傳的文件進行處理,如果有多個文件表單則處理多次for(String key : keys){//原始文件名srcName=fileMap.get(key).getOriginalFilename();if(srcName==null || srcName.equals("")){break;}nameList.add(srcName);//獲得輸出流fos=new FileOutputStream(targetPath+srcName);//把輸入流拷貝到輸出流FileCopyUtils.copy(fileMap.get(key).getInputStream(), fos);}request.setAttribute("userName", userName);request.setAttribute("nameList", nameList);return new ModelAndView("ShowFile");}}

上傳好了的文件的展示

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="scheme" value="${pageContext.request.scheme}"></c:set> <c:set var="serverName" value="${pageContext.request.serverName}"></c:set> <c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set> <c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set> <c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${contextPath}/"></c:set><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="${basePath}"><title>展示上傳文件</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> </head><body> <h2>上傳人:${requestScope.userName }</h2> <c:if test="${not empty requestScope.nameList}"><c:forEach items="${requestScope.nameList}" var="oneName"><h2>文件名:${oneName } <a href="Download.php?fileName=${oneName }">下載</a></h2></c:forEach> </c:if> </body> </html>

二 文件下載

package com.wx.controler.user;import java.io.FileInputStream; import java.net.URLEncoder;import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;@Controller public class DownloadControl {@RequestMapping(value="/Download.php")public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception{String fileName=request.getParameter("fileName");//對a標簽提交的文件名亂碼處理fileName=new String(fileName.getBytes("iso-8859-1"),"utf-8"); System.out.println("theName:"+fileName);HttpSession session=request.getSession();String filePath=session.getServletContext().getRealPath("/uploads")+"\\";FileInputStream fis=new FileInputStream(filePath+fileName);response.setContentType("application/x-msdownload");//表示以下載的方式回復客戶請求fileName=URLEncoder.encode(fileName, "utf-8"); //處理客戶端附件的亂碼問題//設置是以附件的形式下載response.setHeader("Content-Disposition", "attachment;filename="+fileName);//獲得輸出流,該輸出流表示對客戶端請求的反饋ServletOutputStream sos=response.getOutputStream();//拷貝輸入流到輸出流FileCopyUtils.copy(fis, sos);sos.close();fis.close();return null;} }

總結

以上是生活随笔為你收集整理的spring boot基础教程之文件上传下载的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。