相信熟悉struts的朋友对利用struts框架上传文件都非常熟悉了,不过自己在以前有过上传文件后然后加上水印的需求,这次发上来与大家分享一下,希望能给有需要的人一点帮助,高手就无视啦……
这里只发上业务处理部分,视图部分就简单一个jsp页面
FileUploadAction.java
- ........
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response) {
- //拿到文件表单
- FileForm fileForm = (FileForm) form;
- String name=fileForm.getFile().getFileName();//得到文件名
- String realpath=this.getServlet().getServletContext().getRealPath("/")+name;//创建文件的路径名
- try {
- //拿到文件输入流
- InputStream in=fileForm.getFile().getInputStream();
- byte[] buf=new byte[1024*2];
- int length=0;
- //文件输出流
- FileOutputStream out=new FileOutputStream(realpath);
- while((length=in.read(buf))!=-1){
- out.write(buf,0,length);//读进缓冲区,再写入到文件中
- }
- in.close();
- out.close();
- System.out.println("文件上传成功!");
- //用上传成功的图片构件一个流
- FileInputStream ino=new FileInputStream(realpath);
- //将流变为图片
- BufferedImage image=ImageIO.read(ino);
- /*在图片上做手脚(即打水印,说话粗俗了点,呵呵)*/
- Graphics g=image.getGraphics();//拿到图片画笔
- g.setFont(new Font("华文新魏",Font.BOLD,35));
- //水印打的位置
- g.drawString("IvanZhang", image.getWidth()-350,image.getHeight()-35);
- //手脚做好以后,放回原来的位置
- FileOutputStream out2=new FileOutputStream(realpath);
- JPEGImageEncoder enc=JPEGCodec.createJPEGEncoder(out2);//换成JPEG Data streams.
- enc.encode(image);//Encode a BufferedImage as a JPEG data stream.
- //把门关上,神不知鬼不觉
- ino.close();
- out2.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- ..........
表单类:
FileForm.java
- public class FileForm extends ActionForm {
- /** file property */
- private FormFile file;
- /**
- * Method validate
- * @param mapping
- * @param request
- * @return ActionErrors
- */
- public ActionErrors validate(ActionMapping mapping,
- HttpServletRequest request) {
- // TODO Auto-generated method stub
- return null;
- }
- /**
- * Method reset
- * @param mapping
- * @param request
- */
- public void reset(ActionMapping mapping, HttpServletRequest request) {
- // TODO Auto-generated method stub
- }
- /**
- * Returns the file.
- * @return String
- */
- public FormFile getFile() {
- return file;
- }
- /**
- * Set the file.
- * @param file The file to set
- */
- public void setFile(FormFile file) {
- this.file = file;
- }
- }
简单的功能实现,大家不仿试试看,
水印部分用到了
com.sun.image.codec.jpeg包中的内容,有兴趣的朋友可自己查阅相关API