当前位置:首页 » 文件传输 » spring上传图片
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

spring上传图片

发布时间: 2022-02-01 04:19:26

① 关于SpringBoot上传图片的几种方式

1. 直接上传到指定的服务器路径;
2. 上传到第三方内容存储器,这里介绍将图片保存到七牛云
3. 自己搭建文件存储服务器,如:FastDFS,FTP服务器等

② 如何在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可以剪切以上的一部分.请自行调整.

③ 关于spring mvc 上传图片保存到数据库的问题。

文件上传基本思路
1. 在一个 html 网页中,写一个如下的form :
<form method=post encType=multipart/form-data action='xx'>
<input name="userfile1" type="file" ><br>

<input name="userfile2" type="file"><br>

<input name="userfile3" type="file"><br>

<input name="userfile4" type="file"><br>

text field :<input type="text" name="text" value="text"><br>
<input type="submit" value=" 提交 "><input type=reset>
<form>

2. 服务端 servelet 的编写
现在第三方的 http upload file 工具库很多。Jarkata 项目本身就提供了fileupload 包http://jakarta.apache.org/commons/fileupload/
。文件上传、表单项处理、效率问题基本上都考虑到了。在 struts 中就使用了这个包,不过是用 struts 的方式另行封装了一次。这里我们直接使用 fileupload 包。至于struts 中的用法,请参阅 struts 相关文档。
这个处理文件上传的 servelet 主要代码如下:

public void doPost( HttpServletRequest request, HttpServletResponse response ) {

DiskFileUpload diskFileUpload = new DiskFileUpload();

// 允许文件最大长度

diskFileUpload.setSizeMax( 100*1024*1024 );

// 设置内存缓冲大小

diskFileUpload.setSizeThreshold( 4096 );

// 设置临时目录

diskFileUpload.setRepositoryPath( "c:/tmp" );

List fileItems = diskFileUpload.parseRequest( request );

Iterator iter = fileItems.iterator();

for( ; iter.hasNext(); ) {

FileItem fileItem = (FileItem) iter.next();

if( fileItem.isFormField() ) {

// 当前是一个表单项

out.println( "form field : " + fileItem.getFieldName() + ", " + fileItem.getString() );

} else {

// 当前是一个上传的文件

String fileName = fileItem.getName();

fileItem.write( new File("c:/uploads/"+fileName) );

}

}

}

④ spring图片上传页面报400错误

HTTP 400 错误 - 请求无效 (Bad request);出现这个请求无效报错说明请求没有进入到后台服务里;

这个明显是错误的,get请求?后面的参数可能是这样的那。后台根本就不能接受这个东西吧,要不你就拼接成String吧。或者封装成数组对象,用post提交。

⑤ 如何在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:纯手打,望采纳)

⑥ 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实现文件上传

在现在web应用的开发,springMvc使用频率是比较广泛的,现在给大家总结一下springMvc的上传附件的应用,希望对大家有帮助,废话不多说,看效果

准备jar包

4.准备上传代码


@Controller//spring使用注解管理bean
@RequestMapping("/upload")//向外暴露资源路径,访问到该类
public class UploadController {
/**
* 上传功能
* @return
* @throws IOException
*/
@RequestMapping("/uploadFile")//向外暴露资源路径,访问到该方法
public String uploadFile(MultipartFile imgFile,HttpServletRequest req) throws IOException{
if(imgFile != null ){
//获取文件输入流
InputStream inputStream = imgFile.getInputStream();
//随机产生文件名,原因是:避免上传的附件覆盖之前的附件
String randName = UUID.randomUUID().toString();//随机文件名
//获取文件原名
String originalFilename = imgFile.getOriginalFilename();
//获取文件后缀名(如:jpgpng...)
String extension = FilenameUtils.getExtension(originalFilename);
//新名字
String newName = randName+"."+extension;
//获取servletContext
ServletContext servletContext = req.getSession().getServletContext();
//获取根路径
String rootPath = servletContext.getRealPath("/");

File file = new File(rootPath,"upload");
//判断文件是否存在,若不存在,则创建它
if(!file.exists()){
file.mkdirs();
}
//获取最终输出的位置
FileOutputStream fileOutputStream = new FileOutputStream(new File(file,newName));
//上传附件
IOUtils.(inputStream, fileOutputStream);
}
return null;
}
}

⑧ springmvc怎么控制文件上传的类型

spring 里面CommonsMultipartResolver通过配置上传解析器,后台代码通过一个MultipartHttpServletRequest获取上传文件,然后获取文件名称,截取后缀,那样你就可以上传你想要的文件类型,看下面画线的 .

⑨ springmvc 怎么上传图片到相对路径

需要判断下,路径是否存在
if (!file.exists()) {
file.mkdirs();
}

⑩ spring文件上传

万变不离其宗,要实现文件的上传需要对应的JAR包:
1、commons-fileupload-1.2.2.jar
2、commons-io-2.0.1.jar