文档库 最新最全的文档下载
当前位置:文档库 › 图片上传

图片上传

JSP端



CSVFileReader
FileUp


FormBean中将属性定义为FormFile,geter seter 方法依旧.
Action 中的代码如下:实现将图片上传至UPLOAD文件夹内 如果文件大于20K或是宽&高超过规定范围的,会重新勾画.实现对上传图片的控制.
当然这只是测试Action没有跳转页面..

package upload;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.struts.upload.*;
import java.io.IOException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;

import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class UploadAction extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse)throws Exception {
System.out.println("asdasdasdasdasdasd");
UploadForm uploadForm = (UploadForm) actionForm;
FormFile pic = uploadForm.getPic();
String picname = pic.getFileName();
String uploadFileName = servletRequest.getSession()
.getServletContext()
.getRealPath("upload")+"\\"+picname;
File upliadFile = new File(uploadFileName);
BufferedInputStream bis = null;
Image image = null;
BufferedOutputStream bos = null;
try{
if(pic.getFileSize()<2*1024*1024){
bis = new BufferedInputStream(pic.getInputStream());
image = javax.imageio.ImageIO.read(bis);
int width = image.getWidth(null);
int height = image.getHeight(null);
int w = 160;
int h = 120;
if(width>w||height>h){
BufferedImage bi = new BufferedImage(w,h,
BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(image,0,0,w,h,null);
bos = new BufferedOutputStream(new FileOutputStream(
upliadFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bi);
System.out.println(width * height);
}else{
bos = new BufferedOutputStream(new FileOutputStream(upliadFile));
byte[] date = new byte[5*1024];
int len = bis.read(date);
while (len!=-1){
bos.write(date);
len = bis.read(date);
}
}
}
return actionMapping.findForward("ok");
}catch(Exception e){
e.printStackTrace();
} finally {
try {
if (bis != null)
bis.close();
} catch (IOException e1) {

e1.printStackTrace();
}
try {
if (bos != null)
bos.close();
} catch (IOException e2) {

e2.printStackTrace();
}
}

return actionMapping.findForward("ok");
}
}
-----------------------

-----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------
jsp


/**
*enctype="multipart/form-data"
*enctype="multipart/form-data"是上传二进制数据;
*form里面的input的值以2进制的方式传过去,所以request就得不到值了。
*/
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="https://www.wendangku.net/doc/231277631.html,/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="https://www.wendangku.net/doc/231277631.html,/struts/tags-html" prefix="html"%>



JSP for UploadForm form











ActionForm

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.pi__ge.struts.form;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
/**
* MyEclipse Struts
* Creation date: 01-07-2007
*
* XDoclet definition:
* @struts.form name="uploadForm"
*/
public class UploadForm extends ActionForm {
/*
* Generated fields
*/


/** formFile property */
private FormFile formFile;

/*
* Generated Methods
*/

/**
* Returns the formFile.
* @return String
*/
public FormFile getFormFile() {
return formFile;
}

/**
* Set the formFile.
* @param formFile The formFile to set
*/
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
}

Action

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.pi__ge.struts.action;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.pi__ge.struts.form.UploadForm;

/**
* MyEclipse Struts
* Creation date: 01-07-2007
*
* XDoclet definition:
* @struts.action path="/upload" name="uploadForm" input="upload.jsp" scope="request" validate="true"
*/
public class UploadAction extends Action {
/*
* Generated Methods
*/

/**
* Method execute
* @param mapping

* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UploadForm fileForm = (UploadForm) form;
FormFile file = fileForm.getFormFile();
FileOutputStream fileOutput;
System.out.println("****pi__ge****");
try {
fileOutput = new FileOutputStream("D:\\pi__ge\\day_day_up\\apache-tomcat-5.5.17\\apache-tomcat-5.5.17\\webapps\\Upload\\img\\"+file.getFileName());
System.out.println("****pi__ge*2***"+file.getFileName());
fileOutput.write(file.getFileData());
System.out.println("****pi__ge*3***"+file.getFileData().length);
fileOutput.flush();
fileOutput.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}




return mapping.findForward("success");
}
}
----------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------
调用的地方

上传 推荐最佳比例为:(50px*50px)


下面是上传的界面 uploadphoto.jsp

<%@page contentType="text/html; charset=GBK" import="java.util.HashMap"%>


上传图片
 

 商务客图片上传

 请您选择您要上传的图片,图片推荐:50像素*50像素!使用.jpg .gif .bmp格式









 



<%String msg=request.getAttribute("msg")==null?"":request.getAttribute("msg")+"";
if(!msg.equals("")){
%>


<%}%>

接着是FORM 类 uploadphotoForm

package https://www.wendangku.net/doc/231277631.html,er;

/**
*

Title:


*
*

Description:


*
*

Copyright: Copyright (c) 2006


*
*

Company: fishsoft


*
* @author Danny
* @version 1.0
*/
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;

public class uploadphotoForm extends ActionForm {
protected FormFile uploadphoto;
public FormFile getUploadphoto() {
return uploadphoto;
}

public void setUploadphoto(FormFile theFile) {
this.uploadphoto = theFile;
}

public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = null;
//has the maximum length been exceeded?
Boolean maxLengthExceeded =
(Boolean) request.getAttribute(
MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED);

if ( (maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) {
errors = new ActionErrors();
errors.add(
ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("maxLengthExceeded"));
}
return errors;
}



}

这个是action类 uploadphotoAction


1package https://www.wendangku.net/doc/231277631.html,er;
2
3/** *//**
4 *

Title:


5 *
6 *

Description:


7 *
8 *

Copyright: Copyright (c) 2006


9 *
10 *

Company: fishsoft


11 *
12 * @author Danny
13 * @version 1.0
14 */
15import javax.servlet.http.HttpServletRequest;
16import javax.servlet.http.HttpServletResponse;
17import org.apache.struts.action.ActionForm;
18import org.apache.struts.action.ActionMapping;
19import org.apache.struts.action.ActionForward;
20
21import com.onlysoft.txl.*;
22import java.sql.ResultSet;
23import java.util.Map;
24import java.util.HashMap;
25import java.util.ArrayList;
26import java.util.List;
27import com.onlysoft.txl.mail.client.SenderMail;
28import org.apache.struts.Globals;
29import org.apache.struts.action.ActionMessage;
30import org.apache.struts.action.ActionMessages;
31import org.apache.struts.upload.FormFile;
32import java.io.InputStream;
33import java.io.ByteArrayOutputStream;
34import javax.servlet.http.HttpSession;
35import java.io.FileOutputStream;
36import java.io.OutputStream;
37

38public class uploadphotoAction extends BaseAction{
39 public ActionForward execute(
40 ActionMapping mapping,
41 ActionForm form,
42 HttpServletRequest request,
43 HttpServletResponse response) throws Exception {
44 init(request);
45 if (!isLogin) {
46 return mapping.findForward("relogin");
47 }
48 String flag = request.getParameter("flag");
49 String loadpathto = request.getParameter("loadpathto");
50 String filePath = request.getRealPath("/"); //取当前系统路径
51 String pathphoto = loadpathto;
52
53
54 if (form instanceof uploadphotoForm) {//如果form是uploadsForm
55 String encoding = request.getCharacterEncoding();
56 if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
57 {
58 response.setContentType("text/html; charset=GBK");//如果没有指定编码,编码格式为GBk
59 }
60 uploadphotoForm theForm = (uploadphotoForm ) form;
61 FormFile file = theForm.getUploadphoto();//取得上传的文件
62 try {
63 InputStream stream = file.getInputStream(); //把文件读入
64
65 ByteArrayOutputStream baos = new ByteArrayOutputStream();
66
67 if (file.getFileSize() > (200 * 1024)) {
68 request.setAttribute("message", "文件请控制在200K以下!");
69 return mapping.findForward("ErrorInfo");
70 }
71 String contentType = file.getContentType();
72 System.out.println("文件类别:=" + contentType);
73 String filebackstr = "";
74 if (contentType.equals("image/pjpeg")) {
75 filebackstr = ".jpg";
76 } else if (contentType.equals("image/gif")) {
77 filebackstr = ".gif";
78 } else if (contentType.equals("image/bmp")) {
79 filebackstr = ".bmp";
80 } else {
81 request.setAttribute("message", "文件格式不正确!");
82 return mapping.findForward("ErrorInfo");
83 }
84 OutputStream bos = new FileOutputStream(filePath + pathphoto +
85 userid + file.getFileName()); //建立一个上传文件的输出流
86 int bytesRead = 0;
87 byte[] buffer = new byte[8192];
88 while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
89 bos.write(buffer, 0, bytesRead); //将文件写入服务器
90 }
91 bos.close();
92 stream.close();
93 }
94 catch(Exception e){
95 System.err.print(e);
96 }
97 String sql="update sync4j_user set MYFACEPATH='" +pathphoto.replaceFirst("/","") +userid+file.getFileName()+"' where userid="+userid;
98 db.doSql(sql, db.DELETE_MODE, conn);
99
100 }else{
101 request.setAttribute("message", "上传有误");
102 return mapping.findForward("ErrorInfo");
103 }
104
105
106
107 request.setAttribute("msg", "上传成功");
108 return mapping.findForward("loadok");


109
110 }
111}

相关文档