當前位置:首頁 » 文件管理 » spring上傳下載文件

spring上傳下載文件

發布時間: 2023-01-18 02:14:35

㈠ Springboot使用ftp進行文件上傳下載

首先要在阿里雲ECS上搭建ftp伺服器,默認是有vsftpd ,它是 Linux 下的一款小巧輕快、安全易用的 FTP 伺服器軟體。
用下面命令查看是否安裝了vsftpd,阿里雲ECS默認是安裝好的,如果沒有參考網上文章安裝。

新建用戶ftpuser:
useradd ftpuser -d /home/ftpfile

設置用戶密碼:
passwd ftpuser

多數教程裡面使用的標準的ftp maven依賴:

但是我使用的是阿里雲的ECS上安裝的ftp,在進行連接的時候他提示協議不正確,需要使用sftp,所以maven依賴換成了:

㈡ spring文件上傳

萬變不離其宗,要實現文件的上傳需要對應的JAR包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar

㈢ spring mvc中怎麼用commons-fileupload上傳下載文件,好迷茫

我們後台是用hibernate實現的
資料庫對應的實體的類型設為blob類型
用hibernate將二進制流轉為blob類型
Hibernate.createBlob(inputStream)轉為blob

㈣ 請教spring mvc 的文件上傳

springmvc文件上傳
1.加入jar包:
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
lperson.java中加屬性,實現get ,set方法
private String photoPath;
2.創建WebRoot/upload目錄,存放上傳的文件

1 <sf:form id="p" action="saveOrUpdate"
2 method="post"
3 modelAttribute="person"
4 enctype="multipart/form-data">
5
6 <sf:hidden path="id"/>
7 name: <sf:input path="name"/><br>
8 age: <sf:input path="age"/><br>
9 photo: <input type="file" name="photo"/><br>

上面第9行文件上傳框,不能和實體對象屬性同名,類型不同

controller配置

1 12、文件上傳功能實現 配置文件上傳解析器
2 @RequestMapping(value={"/saveOrUpdate"},method=RequestMethod.POST)
3 public String saveOrUpdate(Person p,
4 @RequestParam("photo") MultipartFile file,
5 HttpServletRequest request
6 ) throws IOException{
7 if(!file.isEmpty()){
8 ServletContext sc = request.getSession().getServletContext();
9 String dir = sc.getRealPath(「/upload」); //設定文件保存的目錄
10
11 String filename = file.getOriginalFilename(); //得到上傳時的文件名
12 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
13
14 p.setPhotoPath(「/upload/」+filename); //設置圖片所在路徑
15
16 System.out.println("upload over. "+ filename);
17 }
18 ps.saveOrUpdate(p);
19 return "redirect:/person/list.action"; //重定向
20 }

3.文件上傳功能實現 spring-mvc.xml 配置文件上傳解析器

1 <!-- 文件上傳解析器 id 必須為multipartResolver -->
2 <bean id="multipartResolver"
3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4 <property name="maxUploadSize" value=「10485760"/>
5 </bean>
6
7 maxUploadSize以位元組為單位:10485760 =10M id名稱必須這樣寫

1 映射資源目錄
2 <mvc:resources location="/upload/" mapping="/upload/**"/>

隨即文件名常用的三種方式:
文件上傳功能(增強:防止文件重名覆蓋)
fileName = UUID.randomUUID().toString() + extName;
fileName = System.nanoTime() + extName;
fileName = System.currentTimeMillis() + extName;

1 if(!file.isEmpty()){
2 ServletContext sc = request.getSession().getServletContext();
3 String dir = sc.getRealPath("/upload");
4 String filename = file.getOriginalFilename();
5
6
7 long _lTime = System.nanoTime();
8 String _ext = filename.substring(filename.lastIndexOf("."));
9 filename = _lTime + _ext;
10
11 FileUtils.writeByteArrayToFile(new File(dir,filename), file.getBytes());
12
13 p.setPhotoPath("/upload/"+filename);
14
15 System.out.println("upload over. "+ filename);
16 }

圖片顯示 personList.jsp
1 <td><img src="${pageContext.request.contextPath}${p.photoPath}">${p.photoPath}</td>

㈤ springmvc怎麼上傳文件

spring mvc(註解)上傳文件的簡單例子,這有幾個需要注意的地方
1.form的enctype=」multipart/form-data」 這個是上傳文件必須的
2.applicationContext.xml中 <bean id=」multipartResolver」 class=」org.springframework.web.multipart.commons.CommonsMultipartResolver」/> 關於文件上傳的配置不能少

大家可以看具體代碼如下:

web.xml
[html] view plain
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>webtest</display-name>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/config/applicationContext.xml
/WEB-INF/config/codeifAction.xml
</param-value>
</context-param>

<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/codeifAction.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 攔截所有以do結尾的請求 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.do</welcome-file>
</welcome-file-list>
</web-app>

applicationContext.xml
[html] view plain
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">

<!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation." lazy-init="false" />

<!-- 另外最好還要加入,不然會被 XML或其它的映射覆蓋! -->
<bean class="org.springframework.web.servlet.mvc.annotation." />

<!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前後綴 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

<!-- 支持上傳文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

</beans>

codeifAction.xml
[html] view plain
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true">

<bean id="uploadAction" class="com.codeif.action.UploadAction" />

</beans>

UploadAction.java
[java] view plain
package com.codeif.action;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadAction {

@RequestMapping(value = "/upload.do")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {

System.out.println("開始");
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
// String fileName = new Date().getTime()+".jpg";
System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}

//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);

return "result";
}

}

index.jsp
[html] view plain
<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上傳圖片</title>
</head>
<body>
<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <input type="submit" value="Submit" /></form>
</body>
</html>

WEB-INF/jsp/下的result.jsp
[html] view plain
<%@ page pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上傳結果</title>
</head>
<body>
<img alt="" src="${fileUrl }" />
</body>
</html>

㈥ springmvc怎麼上傳文件

SpringMVC上傳文件的三種方式
前台:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><form name="serForm" action="/SpringMVC006/fileUpload" method="post" enctype="multipart/form-data"><h1>採用流的方式上傳文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form> <form name="Form2" action="/SpringMVC006/fileUpload2" method="post" enctype="multipart/form-data"><h1>採用multipart提供的file.transfer方法上傳文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form> <form name="Form2" action="/SpringMVC006/springUpload" method="post" enctype="multipart/form-data"><h1>使用spring mvc提供的類的方法上傳文件</h1><input type="file" name="file"><input type="submit" value="upload"/></form></body></html>

配置:

<!-- 多部分文件上傳 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="104857600" /> <property name="maxInMemorySize" value="4096" /> <property name="defaultEncoding" value="UTF-8"></property></bean>

後台:
方式一:

/* * 通過流的方式上傳文件 * @RequestParam("file") 將name=file控制項得到的文件封裝成CommonsMultipartFile 對象 */ @RequestMapping("fileUpload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException { //用來檢測程序運行時間 long startTime=System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); try { //獲取輸出流 OutputStream os=new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename()); //獲取輸入流 CommonsMultipartFile 中可以直接得到文件的流 InputStream is=file.getInputStream(); int temp; //一個一個位元組的讀取並寫入 while((temp=is.read())!=(-1)) { os.write(temp); } os.flush(); os.close(); is.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } long endTime=System.currentTimeMillis(); System.out.println("方法一的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; }

方式二:

/* * 採用file.Transto 來保存上傳的文件 */ @RequestMapping("fileUpload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException { long startTime=System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); String path="E:/"+new Date().getTime()+file.getOriginalFilename(); File newFile=new File(path); //通過CommonsMultipartFile的方法直接寫文件(注意這個時候) file.transferTo(newFile); long endTime=System.currentTimeMillis(); System.out.println("方法二的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; }

方式三:

/* *採用spring提供的上傳文件的方法 */ @RequestMapping("springUpload") public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException { long startTime=System.currentTimeMillis(); //將當前上下文初始化給 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext()); //檢查form中是否有enctype="multipart/form-data" if(multipartResolver.isMultipart(request)) { //將request變成多部分request MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request; //獲取multiRequest 中所有的文件名 Iterator iter=multiRequest.getFileNames(); while(iter.hasNext()) { //一次遍歷所有文件 MultipartFile file=multiRequest.getFile(iter.next().toString()); if(file!=null) { String path="E:/springUpload"+file.getOriginalFilename(); //上傳 file.transferTo(new File(path)); } } } long endTime=System.currentTimeMillis(); System.out.println("方法三的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "/success"; }

我們看看測試上傳的時間:
第一次我用一個4M的文件:
fileName:test.rar
方法一的運行時間:14712ms
fileName:test.rar
方法二的運行時間:5ms
方法三的運行時間:4ms

第二次:我用一個50M的文件
方式一進度很慢,估計得要個5分鍾
方法二的運行時間:67ms
方法三的運行時間:80ms

從測試結果我們可以看到:用springMVC自帶的上傳文件的方法要快的多!
對於測試二的結果:可能是方法三得挨個搜索,所以要慢點。不過一般情況下我們是方法三,因為他能提供給我們更多的方法

㈦ 用spring mvc 如何實現對excel文件的下載和上傳

我現在也在做這個,我用的是阿帕奇提供的poi

㈧ springboot多文件上傳

MultipartFile提供了以下方法來獲取上傳文件的信息:

getOriginalFilename,獲取上傳的文件名字;

getBytes,獲取上傳文件內容,轉為位元組數組;

getInputStream,獲取一個InputStream;

isEmpty,文件上傳內容為空,或者根本就沒有文件上傳;

getSize,文件上傳的大小。

transferTo(File dest),保存文件到目標文件系統;

同時上傳多個文件,則使用MultipartFile數組類來接受多個文件上傳:

//多文件上傳 @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)

    @ResponseBody    public String handleFileUpload(HttpServletRequest request){

        List<MultipartFile> files = ((MultipartHttpServletRequest) request)

                .getFiles("file");

        MultipartFile file = null;

        BufferedOutputStream stream = null;

        for (int i = 0; i < files.size(); ++i) {

            file = files.get(i);

            if (!file.isEmpty()) {

                try {

                    byte[] bytes = file.getBytes();

                    stream = new BufferedOutputStream(new FileOutputStream(

                            new File(file.getOriginalFilename())));

                    stream.write(bytes);

                    stream.close();

                } catch (Exception e) {

                    stream = null;

                    return "You failed to upload " + i + " => "                            + e.getMessage();

                }

            } else {

                return "You failed to upload " + i

                        + " because the file was empty.";

            }

        }

        return "upload successful";

    }

可以通過配置application.properties對SpringBoot上傳的文件進行限定默認為如下配置:

spring.servlet.multipart.enabled=true

spring.servlet.multipart.file-size-threshold=0

spring.servlet.multipart.location=

spring.servlet.multipart.max-file-size=1MB

spring.servlet.multipart.max-request-size=10MB

spring.servlet.multipart.resolve-lazily=false

enabled默認為true,既允許附件上傳。

file-size-threshold限定了當上傳文件超過一定長度時,就先寫到臨時文件里。有助於上傳文件不佔用過多的內存,單位是MB或KB,默認0,既不限定閾值。

location指的是臨時文件的存放目錄,如果不設定,則web伺服器提供一個臨時目錄。

max-file-size屬性指定了單個文件的最大長度,默認1MB,max-request-size屬性說明單次HTTP請求上傳的最大長度,默認10MB.

resolve-lazily表示當文件和參數被訪問的時候再被解析成文件。

㈨ springboot zip文件上傳無法解壓

解決方法如下:
1、使用xshell登錄伺服器。
2、安裝lrzsz軟體。
3、使用rz-y命令然後進行文件上傳。
4、使用sz命令下載,命令格式如下,之後就可以重新試一下文件上傳後能不能解壓。

㈩ SpringBoot + SFTP 實現文件上傳與下載實戰

SFTP介紹

實戰

1. 相關依賴(基於SpringBoot)

2. 相關配置

3. 將application.properties中配置轉為一個Bean

4. 將上傳下載文件封裝成Service

5. 上傳文件

6. 下載文件

7. 刪除文件

8. 最後

熱點內容
編程用的輸入法 發布:2025-09-09 22:18:31 瀏覽:781
安卓機怎麼上卡 發布:2025-09-09 21:30:16 瀏覽:525
編譯運行後一閃而過 發布:2025-09-09 21:28:45 瀏覽:199
哪裡可以搜到關於安卓的設計 發布:2025-09-09 21:28:07 瀏覽:65
安卓手機怎麼搞蘋果手機emoji 發布:2025-09-09 21:09:49 瀏覽:528
安卓手機忘記密碼用什麼軟體刷機 發布:2025-09-09 20:52:48 瀏覽:19
手機存儲8128夠用嗎 發布:2025-09-09 20:47:26 瀏覽:857
存儲池消失 發布:2025-09-09 20:45:59 瀏覽:178
xshell如何配置串口 發布:2025-09-09 20:24:18 瀏覽:847
演算法崗讀博 發布:2025-09-09 20:24:17 瀏覽:977