当前位置:首页 » 文件管理 » smartupload上传图片

smartupload上传图片

发布时间: 2024-02-24 12:04:00

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

2. java 中如何向服务器上传图片

我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}

3. jsp中,我在一个页面,用jspsmartupload上传图片,上传成功后,跳回来,想显示此图,但是显示不出来。

1.上传失败,图片字节大小为0KB,需重新上传覆盖。
2.源文件的所在的目录路径不对。
3.图片命名的格式不支持:不要用汉字为图片命名,最好是纯英文字母,一般数字也可以。
不知道能帮上不

4. 跪求使用smartupload组件实现图片上传的最简单的jsp代码

<%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
<jsp:directive.page import="org.lxh.smart.SmartUpload"/>
<jsp:directive.page import="java.io.File"/>
<jsp:directive.page import="org.lxh.smart.Files"/>
<jsp:directive.page import="com..PathDao"/>
<jsp:directive.page import="com.entity.Photo"/>
<jsp:directive.page import="java.util.List"/>
<jsp:directive.page import="java.util.ArrayList"/>
<jsp:directive.page import="com..PhotoDao"/>
<jsp:directive.page import="com.impl.PhotoDaoImpl"/>
<%
int albumId=8;
int uId=Integer.parseInt(session.getAttribute("user").toString());
List<Photo> listPhoto=new ArrayList<Photo>();
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
try{
// 上传初始化
su.initialize(pageContext);
// 设定上传限制
// 1.限制每个上传文件的最大长度。
//su.setMaxFileSize(10000);
// 2.限制总上传数据的长度。
//su.setTotalMaxFileSize(20000);
// 3.设定允许上传的文件(通过扩展名限制)。
//su.setAllowedFilesList("gif,jpg,png,GIF,JPG,PNG");
// 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat,
//jsp,htm,html扩展名的文件和没有扩展名的文件。
//su.setDeniedFilesList("exe,bat,jsp,htm,html,,");
// 上传文件
su.upload();
// 将上传文件全部保存到指定目录
String temp="/upload/images/"+session.getAttribute("user");
//创建文件夹使用绝对路径
String uploadPath =request.getRealPath("/")+temp;
if(!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs();
Files files=su.getFiles();
for(int i=0;i<files.getCount();i++){
org.lxh.smart.File file=files.getFile(i);
if(file.isMissing()){break;}
if(i>1){
if(file==files.getFile(i-1)){
continue;
}
if(i>2){
if(file==files.getFile(i-2)){
continue;
}
}
if(i>3){
if(file==files.getFile(i-3)){
continue;
}
}
}
PathDao pathDao=new PathDao();//这个类里面实现一个getFileName方法,根据当前时间得到图片名称
String postfix="."+file.getFileExt();
//这个就是可以得到图片的路径了
String strtemp=uploadPath+"/"+pathDao.getFileName()+postfix;
file.saveAs(strtemp);
}
%>
<script>
alert("图片上传成功!");
</script>
<%
}catch (Exception e){
System.out.println(e.getMessage());
%>
<script>
alert("图片上传失败!");
history.go(-1);
</script>
<%
}finally{
%>
<script>location="toYours.jsp?name=album.jsp";</script>
<%
}
%>

------------jsp页面--------
<FORM METHOD="POST" ACTION="do_uploadPhotos.jsp"
ENCTYPE="multipart/form-data" name="uploadPhotoForm"
onSubmit="return check()">
<table width="75%" border="1" align="center">
<tr>
<td>
<div align="center">
1、
<input type="FILE" name="FILE1" size="30">
</div>
</td>
</tr>
<tr>
<td>
<div align="center">
2、
<input type="FILE" name="FILE2" size="30">
</div>
</td>
</tr>
<tr>
<td>
<div align="center">
3、
<input type="FILE" name="FILE3" size="30">
</div>
</td>
</tr>
<tr>
<td>
<div align="center">
4、
<input type="FILE" name="FILE4" size="30">
</div>
</td>
</tr>
<tr>
<td>
<div align="center">
<input type="submit" name="Submit1" value="上传图片">
</div>
</td>
</tr>
</table>

</FORM>

5. JSP如何上传图片

如果你是纯JSP写的,可以用SmartUpload.在你的页面form 里 <form action="doUpload.jsp" method="POST" enctype="multipart/form-data">
文件名:<input type="text" name="name"/><br>
请选择上传的文件:<input type="file" name="file1"/>
<input type="submit" value="上传"/>
</form> 注意:enctype="multipart/form-data"这个一定要这样设置,具体什么意思我也不是很清楚.....(呵呵) 提交到执行的页面如下: //实例化上传组件
SmartUpload upload = new SmartUpload();
//初始化上传组件
upload.initialize(this.getServletConfig(), request, response);
//开始上传
upload.upload();
//获取上传的文件列表对象
Files f = upload.getFiles();
//获取文件对象
File fil = f.getFile(0);
//去掉文件后缀
String ext = fil.getFileExt();
//判断文件类型是否是jpg格式jpg,gif,bmp,png,JPG,GIF,BMP,PNG
if (!(ext.equals("jpg")) && !(ext.equals("gif")) && !(ext.equals("bmp")) && !(ext.equals("png")) && !(ext.equals("JPG")) && !(ext.equals("GIF")) && !(ext.equals("BMP")) && !(ext.equals("PNG"))) {
out.println("<script type='text/javascript'>alert('文件类型错误');location.replace('upLoadPhoto.jsp');</script>");
return;
}
//满足条件进行文件的上传uploadImages在webRoot文件夹下的一个目录
fil.saveAs("uploadImages/" + fil.getFileName());
String filepath = "uploadImages/" + fil.getFileName(); //保存到数据库的路径 OK.这样就可以了.....

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

7. jsp如何将图片上传到服务器某个文件夹里面,而路径存到数据库中!!请教!!!

用smartupload 控件来完成 你网络下一大堆的例子,算了我帮你网络,不然你分不给我,要记的给我呀,至于保存在数据库中,你可以用年月日时分秒这样的格式生成一个文件存放目录,将图片的路径保存到数据库中

<%@ page language="java" contentType="text/html; charset=GB2312" pageEncoding="GB2312"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="com.jspsmart.upload.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
<title>文件上传Bean</title>
</head>
<body>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<FORM METHOD="POST" ACTION="Ex7_7.jsp" ENCTYPE="multipart/form-data">
<INPUT TYPE="FILE" NAME="FILE1" SIZE="50"><BR>
<INPUT TYPE="FILE" NAME="FILE2" SIZE="50"><BR>
<INPUT TYPE="FILE" NAME="FILE3" SIZE="50"><BR>
<INPUT TYPE="FILE" NAME="FILE4" SIZE="50"><BR>
<INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM>
<%
//上传文件计数
int count=0;
//初始化,传入pageContext内置变量
mySmartUpload.initialize(pageContext);
//允许上传的文件类型
mySmartUpload.setAllowedFilesList("htm,html,txt,jar,");

//或者设定拒绝上传的文件类型
// mySmartUpload.setDeniedFilesList("exe,bat,jsp");

// 拒绝的物理路径
// mySmartUpload.setDenyPhysicalPath(true);

// 设置文件最大为 50000 bytes
mySmartUpload.setMaxFileSize(50000);

// 允许一次最多上载文件大小不超过 200000 bytes
// mySmartUpload.setTotalMaxFileSize(200000);
try {
// 上传操作
mySmartUpload.upload();
//以原文件名存储在web服务器虚拟路径下
//返回上传的文件数
count = mySmartUpload.save("/Upload", mySmartUpload.SAVE_VIRTUAL);
} catch (Exception e){
//输出意外信息
out.println("<b>Wrong selection : </b>" + e.toString());
}
// 显示文件上载数
out.println(count + " file(s) uploaded.");
%>
</body>
</html>

热点内容
共享云源码 发布:2024-09-08 10:01:10 浏览:393
ios应用上传 发布:2024-09-08 09:39:41 浏览:439
ios储存密码哪里看 发布:2024-09-08 09:30:02 浏览:873
opensslcmake编译 发布:2024-09-08 09:08:48 浏览:653
linux下ntp服务器搭建 发布:2024-09-08 08:26:46 浏览:744
db2新建数据库 发布:2024-09-08 08:10:19 浏览:173
频率计源码 发布:2024-09-08 07:40:26 浏览:780
奥迪a6哪个配置带后排加热 发布:2024-09-08 07:06:32 浏览:101
linux修改apache端口 发布:2024-09-08 07:05:49 浏览:209
有多少个不同的密码子 发布:2024-09-08 07:00:46 浏览:566