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

java图片上传预览

发布时间: 2024-06-12 19:49:00

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

㈡ 用Java Web的jsp制作图片上传和显示如何实现

用jspSmartUpload组件来实现,用jsp+servlet在Servlet里实现的代码:

PrintWriter out = response.getWriter();
int count = 0;
// 实例化亏友上传控件对象
SmartUpload su = new SmartUpload();
// 初始化操作
su.initialize(config, request, response);

// 设置上传文件最大字节数
su.setTotalMaxFileSize(100000);

//
try {
//禁止上传指定扩展和空唤名的文件
su.setDeniedFilesList("ext,bat,jsp");
} catch (SQLException e1) {
e1.printStackTrace();
}

try {
// 上传文件到服务器
su.upload();

File fileup = new File(request.getRealPath("upload"));
if(!fileup.exists()){
// 创建目录
fileup.mkdir();
}
// 处理多个文件的上传
for(int i = 0;i < su.getFiles().getCount();i++){
com.jspsmart.upload.File file = su.getFiles().getFile(i);
if(!file.isMissing()){ // 如果文件有效
// 保存文件到指定上传目录
file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);
count = su.save("/upload");
}
}

} catch (SmartUploadException e) {

e.printStackTrace();
}
out.println(count +"file(s) uploaded");

如果你对这个上唤凯传组件不了解,最好是先去查查用法。。。

㈢ java上传图片 生成缩略图,如果上传的图片尺寸比较小就压缩处理

//将图按比例缩小。
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
//这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
//则将下面的if else语句注释即可
if(sx>sy)
{
sx = sy;
targetW = (int)(sx * source.getWidth());
}else{
sy = sx;
targetH = (int)(sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { //handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}

public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)
throws Exception {
BufferedImage srcImage;
// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
String imgType = "JPEG";
if (fromFileStr.toLowerCase().endsWith(".png")) {
imgType = "PNG";
}
// System.out.println(ex);
File saveFile=new File(saveToFileStr);
File fromFile=new File(fromFileStr);
srcImage = ImageIO.read(fromFile);
if(width > 0 || hight > 0)
{
srcImage = resize(srcImage, width, hight);
}
ImageIO.write(srcImage, imgType, saveFile);

}

public static void main (String argv[]) {
try{
//参数1(from),参数2(to),参数3(宽),参数4(高)
saveImageAsJpg("C:\\Documents and Settings\\xugang\\桌面\\tmr-06.jpg",
"C:\\Documents and Settings\\xugang\\桌面\\2.jpg",
120,120);
} catch(Exception e){
e.printStackTrace();
}

}

㈣ 请问用Java 如何实现图片上传功能

自己写程序来上传字节流文件很难的,用SmartUpload.jar包吧,专门用于JSP上传下载的,唯一缺点就是中文支持不太好,不过你可以改一下原程序的字符集就行了。上网搜,没有找我!我给你发

㈤ java实现图片上传至服务器并显示,如何做希望要具体的代码实现

很简单。
可以手写IO读写(有点麻烦)。
怕麻烦的话使用FileUpload组件 在servlet里doPost嵌入一下代码
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();

//设置保存上传文件的目录
String uploadDir =getServletContext().getRealPath("/up");
System.out.println(uploadDir);
if (uploadDir == null)
{
out.println("无法访问存储目录!");
return;
}
//根据路径创建一个文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目录不存在 创建一个 不能创建输出...
{
out.println("无法创建存储目录!");
return;
}
}

if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能处理multipart/form-data类型的数据!");
return ;
}

DiskFileUpload fu = new DiskFileUpload();
//最多上传200M数据
fu.setSizeMax(1024 * 1024 * 200);
//超过1M的字段数据采用临时文件缓存
fu.setSizeThreshold(1024 * 1024);
//采用默认的临时文件存储位置
//fu.setRepositoryPath(...);
//设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
fu.setHeaderEncoding("gb2312");

//得到所有表单字段对象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request对象中上传的文件

}
catch (FileUploadException e)
{
out.println("解析数据时出现如下问题:");
e.printStackTrace(out);
return;
}

//处理每个表单字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField()){
String content = fi.getString("GB2312");
String fieldName = fi.getFieldName();
request.setAttribute(fieldName,content);
}else{
try
{
String pathSrc = fi.getName();
if(pathSrc.trim().equals("")){
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName);

fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
}catch (Exception e){
out.println("存储文件时出现如下问题:");
e.printStackTrace(out);
return;
}
finally //总是立即删除保存表单字段内容的临时文件
{
fi.delete();
}

}
}
注意 JSP页面的form要加enctype="multipart/form-data" 属性, 提交的时候要向服务器说明一下 此页面包含文件。

如果 还是麻烦,干脆使用Struts 的上传组件 他对FileUpload又做了封装,使用起来更傻瓜化,很容易掌握。

-----------------------------
以上回答,如有不明白可以联系我。

㈥ java实现图片上传至服务器并显示,如何做

给你段代码,是用来在ie上显示图片的(servlet):

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
File file = new File(getServletContext().getRealPath("/")+"out"+"/"+id+".gif");
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));

System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));

OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);

byte[] b = new byte[1024];
int i = 0;

while((i = fis.read(b))!=-1)
{

output.write(b, 0, i);
}
output.write(b, 0, b.length);

output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}

}

这个程序的功能是根据传入的文件名(id),来为浏览器返回图片流,显示在<img>标签里
标签的格式写成如下:
<img src="http://localhost:8080/app/preview?id=111 "/><br/>
显示的是111.gif这个图片

你上面的问题:
1.我觉得你的第二个办法是对的,我们也是这样做的,需要的是把数据库的记录id号传进servlet,然后读取这条记录中的路径信息,生成流以后返回就是了

关于上传文件的问题,我记得java中应该专门有个负责文件上传的类,你调用就行了,上传后存储在指定的目录里,以实体文件的形式存放
你可以参考这个:
http://blog.csdn.net/arielxp/archive/2004/09/28/119592.aspx

回复:
1.是的,在response中写入流就行了
2.是发到servlet中的,我们一般都是写成servlet,短小精悍,使用起来方便,struts应该也可以,只是我没有试过,恩,你理解的很对

㈦ Java在jsp中 如何上传图片 在上传时可以取到图片大小并修改

用第三方工具去取 common-upload,具体取到图片的方法参考代码如下:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
upload.setHeaderEncoding("utf-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
System.out.println("fileName=" + fileItem.getFieldName());
//获取文件流
InputStream in = fileItem.getInputStream();
ServletContext context = getServletConfig().getServletContext();
String path = context.getRealPath("image");
System.out.println(path);
OutputStream out = new FileOutputStream(new File(path + "\\" + fileItem.getName()));
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("写入完毕");
}
} catch (FileUploadException e) {
e.printStackTrace();
}

㈧ 我用java写了个上传图片的功能,上传后为什么只有重启tomcat后,图片才能显示呢

不能把文件传到项目的工作空间去了,应该传到tomcat对应的项目下才行.
比如我的tomcat装在c盘下的,那么在路径C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps下会有个和工作空间里项目一样名称的文件夹,得把文件传到这里.

热点内容
安卓手机如何使用手写功能 发布:2024-10-22 23:19:16 浏览:351
手机壁纸上传 发布:2024-10-22 23:13:51 浏览:772
oracle数据库迁移方案 发布:2024-10-22 23:10:53 浏览:384
七牛云存储java上传 发布:2024-10-22 23:10:49 浏览:236
kvm编译原理 发布:2024-10-22 22:57:41 浏览:441
qq密码情侣改成什么最好 发布:2024-10-22 22:55:48 浏览:809
linux安装cuda 发布:2024-10-22 22:32:07 浏览:487
编译和链接的键 发布:2024-10-22 22:21:01 浏览:115
java数组的实现 发布:2024-10-22 22:18:15 浏览:330
python定义字符串数组 发布:2024-10-22 22:14:26 浏览:605