---
title: "web开发之上传图片备忘"
author: "bit6211"
date: "2009-12-10T13:18:38Z"
tags: []
categories: ["互联网"]
slug: "web"
draft: false
lastmod: "2009-12-10T13:20:46Z"
id: 545430
url: "https://bit6211.iteye.com/blog/545430"
---

:D 把图片上传到服务器，然后在前端页面显示查看的方法很多，作为一个入门的程序员，我把用到过的方法记录如下。
    方法一，用struts 1上传图片。步骤如下：
    1 创建一个ActionForm。
public class MessForm extends ActionForm
{	
	private FormFile photo; 

	public FormFile getPhoto()
	{
		return photo;
	}

	public void setPhoto(FormFile photo)
	{
		this.photo = photo;
	}
}
    其中FormFile用来存放上传的图片。
    2 创建一个Action。
    public class AddAction extends Action
{
	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		// TODO Auto-generated method stub
		MessForm mf = (MessForm) form;

		FormFile photo = mf.getPhoto();
		String photoPath = this.getServlet().getServletContext().getRealPath("/") + "upload\\" + photo.getFileName();//存储目录，可以在配置文件里设置，这样可以方便更改存储目录
		
		FileOutputStream fos = new FileOutputStream(photoPath);
		fos.write(photo.getFileData());
		fos.flush();
		fos.close();
							   	         return mapping.findForward("add");

	}
	
}
    3 写配置文件struts-config.xml。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

<struts-config>
  <data-sources />
  <form-beans>
  	<form-bean name="messForm" type="com.model.MessForm"></form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards />
  <action-mappings>
    	<action
  		path="/cadd"
  		parameter="sc"
  		type="com.action.AddAction"
  		name="messForm">
  		<forward name="add" path="/science/find.jsp"/>
  	</action>
  	
  </action-mappings>
  <message-resources parameter="ApplicationResources" />
</struts-config>
    这样就可以把图片上传到服务器了。


    方法二，用struts 2上传图片。步骤如下：
     1 创建一个Action。
public class RegisterAction extends ActionSupport
{
		
	//封装上传文件域的属性
	private File photo;
	//封装上传文件类型的属性
	private String photoContentType;
	//封装上传文件名的属性
	private String photoFileName;
	//接受依赖注入的属性
	private String savePath;
	
	public File getPhoto()
	{
		return photo;
	}
	public void setPhoto(File photo)
	{
		this.photo = photo;
	}
	public String getPhotoContentType()
	{
		return photoContentType;
	}
	public void setPhotoContentType(String photoContentType)
	{
		this.photoContentType = photoContentType;
	}
	public String getPhotoFileName()
	{
		return photoFileName;
	}
	public void setPhotoFileName(String photoFileName)
	{
		this.photoFileName = photoFileName;
	}
	public String getSavePath()
	{
		return ServletActionContext.getRequest().getRealPath(savePath);
	}
	public void setSavePath(String savePath)
	{
		this.savePath = savePath;
	}

         @Override
	public String execute() throws Exception
	{
		// TODO Auto-generated method stub
		//以服务器的文件保存地址和原文件名建立上传文件输出流
		FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getPhotoFileName());
		
		//以上传文件建立一个文件上传流
		FileInputStream fis = new FileInputStream(getPhoto());
		//将上传文件的内容写入到服务器
		byte buffer = new byte;
		int len = 0;
		while((len = fis.read(buffer)) > 0)
		{
			fos.write(buffer, 0, len);
		}
                   return SUCCESS;
				
	}	
}

    2 写配置文件struts.xml。
     <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE struts PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
          "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<!-- 国际化资源文件 -->
	<constant name="struts.custom.i18n.resources" value="globalMessages"></constant>
    <package name="mypackage" extends="struts-default">
        <action name="register" class="org.chh.controller.RegisterAction">
        	<interceptor-ref name="fileUpload">
        		<param name="allowedTypes">image/bmp,image/png/,image/gif,image/jpeg,image/jpg</param>
        		<param name="maximumSize">10240</param>
        	</interceptor-ref>
        	<interceptor-ref name="defaultStack"></interceptor-ref>
        	
        	<param name="savePath">/upload</param>
            <result name="success">information.jsp</result>
            <result name="input">register.jsp</result>
        </action>
    </package>
    
</struts>
    这样就可以把图片上传到服务器了。
     
    上面两种方法只是把图片上传到服务器的某个目录，并没有把图片保存到数据库中，这种做法有个缺陷，就是两张图片名字相同的时候，最后上传的图片会把之前的图片覆盖掉。我们可以通过产生一个大的不重复的随机数，然后把这个随机数连接在图片名字的后面，来确保图片名字唯一。或者通过java.util.UUID类产生一个UUID连接在图片名字后面也行。当然，最好的做法是把图片存入数据库了。

    图片上传到服务器后，就可以在客户端显示了，一个简单的jsp代码如下：
<%
					String path = request.getContextPath();
					String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"+"upload/相片名";
									%>
					<img src="<%=basePath %>width="129" height="150"/>
 :D