当前位置:首页 » 文件管理 » springmvc上传下载

springmvc上传下载

发布时间: 2023-03-17 16:34:44

A. SpringMVC使用commons fileupload 上传文件,parseRequest(request)得到的集合为空,急等大神指点。

既然你已经用了Spring MVC,就没有必要自己写上传的代码了,这样做
下一个这样的方法,把MultipartFile传进去
public String upload(@RequestParam(value = "image") MultipartFile image)
然后就可以这样做了
image.transferTo(new File("想要保存到哪里"));

image还有其他的方法,自己看一下就可以了

XML配置一个bean

<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" />
</bean>

B. spring mvc word文件上传之后可预览的实现方法或者步骤

你好!
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>

C. 如何在spring mvc中上传图片并显示出来

可以使用组件上传JspSmartUpload.这是一个类.

<form name="f1" id="f1" action="/demo/servlet/UploadServlet" method="post" enctype="multipart/form-data">

<table border="0">

<tr>

<td>用户名:</td>

<td><input type="text" name="username" id="username"></td>

</tr>

<tr>

<td>密码:</td>

<td><input type="password" name="password" id="password"></td>

</tr>

<tr>

<td>相片:</td>

<td><input type="file" name="pic" id="pic"></td>

</tr>

<tr>

<td>相片:</td>

<td><input type="file" name="pic2" id="pic2"></td>

</tr>

<tr>

<td colspan="2" align="center"><input type="submit"></td>

</tr>

</table>

</form>

这里直接通过表单提交给servlet访问,spring中的话需要配置(一般就不用servlet了,自行配置).

以上在JSp页面中,以下是servlet/action中的代码,由于采用了spring框架,怎么做你知道的(没有servlet但是有action).

package com.demo.servlet;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Random;

import java.util.UUID;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.File;

import com.jspsmart.upload.Files;

import com.jspsmart.upload.Request;

import com.jspsmart.upload.SmartUpload;

public class UploadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

SmartUpload su = new SmartUpload();

//初始化

su.initialize(this.getServletConfig(), request, response);

try {

//限制格式

//只允许哪几种格式

su.setAllowedFilesList("jpg,JPG,png,PNG,bmp,gif,GIF");

//不允许哪几种格式上传,不允许exe,bat及无扩展名的文件类型

//su.setDeniedFilesList("exe,bat,,");

//限制大小,每个上传的文件大小都不能大于100K

su.setMaxFileSize(100*1024);

//上传文件的总大小不能超过100K

//su.setTotalMaxFileSize(100*1024);

//上传

su.upload();

//唯一文件名

//得到文件集合

Files files = su.getFiles();

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

{

//获得每一个上传文件

File file = files.getFile(i);

//判断客户是否选择了文件

if(file.isMissing())

{

continue;

}

//唯一名字

Random rand = new Random();

//String fileName = System.currentTimeMillis()+""+rand.nextInt(100000)+"."+file.getFileExt();

String fileName = UUID.randomUUID()+"."+file.getFileExt();

//以当前日期作为文件夹

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String dirPath = sdf.format(new Date());

//获得物理路径

String realDirPath= this.getServletContext().getRealPath(dirPath);

java.io.File dirFile = new java.io.File(realDirPath);

//判断是否存在

if(!dirFile.exists())

{

//创建文件夹

dirFile.mkdir();

}

//保存

file.saveAs("/"+dirPath+"/"+fileName);

//file.saveAs("/uploadFiles/"+fileName);

}

//原名保存

//su.save("/uploadFiles");

} catch (Exception e) {

System.out.println("格式错误");

}

//获得用户名

Request req = su.getRequest();

String username = req.getParameter("username");

System.out.println(username);

}

/**

* The doPost method of the servlet. <br>

*

* This method is called when a form has its tag value method equals to post.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

this.doGet(request, response);

}

}

特别注意导的包是JspSmartUpload中的还是java.io.*中的.

再次说明,这段代码是servlet中的,spring中的action可以剪切以上的一部分.请自行调整.

D. springmvc 怎么将文件上传到linux服务器

Spring MVC为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver实现的。Spring使用Jakarta Commons FileUpload 技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。
Spring MVC上下文中默认没有装配MultipartResolver,因此默认情况下不能处理文件的上传工作。如果想要使用Spring的文件上传功能,需要先在上下文中配置MultipartResolver。
第一步:配置MultipartResolver
使用CommonsMultipartResolver配置一个MultipartResolver解析器:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="5242880"
p:uploadTempDir="upload/temp"
/>

defaultEncoding必须和用户JSP的pageEncoding属性一致,以便正确读取表单的内容。uploadTempDir是文件上传过程所使用的临时目录,文件上传完成后,临时目录中的临时文件会被自动清除。
第二步:编写文件上传表单页面和控制器
JSP页面如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<h1>选择上传文件</h1>
<form action="<%=basePath%>user/upload.do" method="post" enctype="multipart/form-data">
文件名:<input type="text" name="name" /><br/>
<input type="file" name="file" /><br/>
<input type="submit" />
</form>
</body>
</html>

注意:负责上传的表单和一般表单有一些区别,表单的编码类型必须是"Multipart/form-data"
控制器UserController如下:

package com.web;

import java.io.File;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@RequestMapping(value = "/upload.do")
public String updateThumb(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file)
throws IllegalStateException, IOException {
if (!file.isEmpty()) {
file.transferTo(new File("d:/temp/"
+ name
+ file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."))));
return "redirect:success.html";
} else {
return "redirect:fail.html";
}
}
}

Spring MVC会将上传文件绑定到MultipartFile对象中。MultipartFile提供了获取上传文件内容、文件名等内容,通过transferTo方法还可将文件存储到硬件中,具体说明如下:
byte[] getBytes() :获取文件数据
String getContentType():获取文件MIME类型,如image/pjpeg、text/plain等
InputStream getInputStream():获取文件流
String getName():获取表单中文件组件的名字
String getOriginalFilename():获取上传文件的原名
long getSize():获取文件的字节大小,单位为byte
boolean isEmpty():是否有上传的文件
void transferTo(File dest):可以使用该文件将上传文件保存到一个目标文件中
源码:uploadtest.zip

E. 如何在spring mvc中上传图片并显示出来

(1)在spring mvc的配置文件中配置:

<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="uploadTempDir"value="/tmp"/><!--临时目录-->
<propertyname="maxUploadSize"value="10485760"/><!--10M-->
</bean>

(2)文件上传表单和结果展示页fileupload.jsp:

<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglibprefix="mvc"uri="http://www.springframework.org/tags/form"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>SpringMVC文件上传</title>
</head>
<body>
<h2>图片文件上传</h2>
<mvc:formmodelAttribute="user"action="upload.html"
enctype="multipart/form-data">
<table>
<tr>
<td>用户名:</td>
<td><mvc:inputpath="userName"/></td>
</tr>
<tr>
<td>选择头像:</td>
<td><inputtype="file"name="file"/></td>
</tr>
<tr>
<tdcolspan="2"><inputtype="submit"value="Submit"/></td>
</tr>
</table>
</mvc:form>
<br><br>
<c:iftest="${u!=null}">
<h2>上传结果</h2>
<table>
<c:iftest="${u.userName!=null}">
<tr>
<td>用户名:</td>
<td>${u.userName}</td>
</tr>
</c:if>
<c:iftest="${u.logoSrc!=null}">
<tr>
<td>头像:</td>
<td><imgsrc="${u.logoSrc}"width="100px"height="100px"></td>
</tr>
</c:if>

</table>

</c:if>

</body>
</html>

(3)后台处理UploadController.java:

packagecn.zifangsky.controller;

importjava.io.File;
importjava.io.IOException;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.commons.io.FileUtils;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.servlet.ModelAndView;

importcn.zifangsky.model.User;
importcn.zifangsky.utils.StringUtile;

@Controller
publicclassUploadController{

@RequestMapping(value="/form")
publicModelAndViewform(){
ModelAndViewmodelAndView=newModelAndView("fileupload","user",newUser());

returnmodelAndView;
}

@RequestMapping(value="/upload",method=RequestMethod.POST)
publicModelAndViewupload(Useruser,@RequestParam("file")MultipartFiletmpFile,HttpServletRequestrequest){
ModelAndViewmodelAndView=newModelAndView("fileupload");

if(tmpFile!=null){
//获取物理路径
StringtargetDirectory=request.getSession().getServletContext().getRealPath("/uploads");
StringtmpFileName=tmpFile.getOriginalFilename();//上传的文件名
intdot=tmpFileName.lastIndexOf('.');
Stringext="";//文件后缀名
if((dot>-1)&&(dot<(tmpFileName.length()-1))){
ext=tmpFileName.substring(dot+1);
}
//其他文件格式不处理
if("png".equalsIgnoreCase(ext)||"jpg".equalsIgnoreCase(ext)||"gif".equalsIgnoreCase(ext)){
//重命名上传的文件名
StringtargetFileName=StringUtile.renameFileName(tmpFileName);
//保存的新文件
Filetarget=newFile(targetDirectory,targetFileName);

try{
//保存文件
FileUtils.InputStreamToFile(tmpFile.getInputStream(),target);
}catch(IOExceptione){
e.printStackTrace();
}

Useru=newUser();
u.setUserName(user.getUserName());
u.setLogoSrc(request.getContextPath()+"/uploads/"+targetFileName);

modelAndView.addObject("u",u);
}

returnmodelAndView;
}

returnmodelAndView;
}

}

在上面的upload方法中,为了接收上传的文件,因此使用了一个MultipartFile类型的变量来接收上传的临时文件,同时为了给文件进行重命名,我调用了一个renameFileName方法,这个方法的具体内容如下:

/**
*文件重命名
*/
(StringfileName){
StringformatDate=newSimpleDateFormat("yyMMddHHmmss").format(newDate());//当前时间字符串
intrandom=newRandom().nextInt(10000);
Stringextension=fileName.substring(fileName.lastIndexOf("."));//文件后缀

returnformatDate+random+extension;
}

注:上面用到的model——User.java:

packagecn.zifangsky.model;

publicclassUser{
privateStringuserName;//用户名
privateStringlogoSrc;//头像地址

publicStringgetUserName(){
returnuserName;
}

publicvoidsetUserName(StringuserName){
this.userName=userName;
}

publicStringgetLogoSrc(){
returnlogoSrc;
}

publicvoidsetLogoSrc(StringlogoSrc){
this.logoSrc=logoSrc;
}

}

至此全部结束

效果如下:

(PS:纯手打,望采纳)

F. spring mvc上传文件表单同时传值的问题

当在上传表单中设置了 enctype="multipart/form-data" 时post传过去的字符串的值为null,会报 HTTP Status 400 - Required String parameter 'description' is not present 错误。
解决方案:
1、首先在pom.xml中添加

然后在applicationContext.xml中添加即可解决,这样的话spring会对表单的数据进行处理,就算使用了enctype="multipart/form-data"进行传值也能拿到数据

热点内容
linux支持线程 发布:2025-05-17 21:26:14 浏览:182
元神队伍配置都由什么组成 发布:2025-05-17 21:20:18 浏览:476
闲鱼和安卓哪个赚钱 发布:2025-05-17 21:15:56 浏览:583
c语言一个c源程序 发布:2025-05-17 21:11:44 浏览:314
如何加密手机的文件 发布:2025-05-17 21:11:43 浏览:916
ios开发文件上传 发布:2025-05-17 21:10:40 浏览:983
g92编程 发布:2025-05-17 21:00:31 浏览:170
汇编语言第三版脚本之家 发布:2025-05-17 20:54:26 浏览:399
资源配置最佳状态叫什么 发布:2025-05-17 20:48:58 浏览:84
定义dns服务器的ip 发布:2025-05-17 20:32:37 浏览:954