spring上传下载文件
首先要在阿里云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. 最后