struts2多文件上传(修改名称、压缩图片、删除图片)

一下代码已经测试过,放心使用:

  ----------------upload.jsp-------------------------

<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>使用数组上传多个文件</title>
</head>
<body>
<s:fielderror/>
<form action="upload.action" method="post" enctype="multipart/form-data">
   文件标题:<input type="text" name="title" /><br>
   选择第一个文件:<input type="file" name="upload" /><br>
   选择第二个文件:<input type="file" name="upload" /><br>
   选择第三个文件:<input type="file" name="upload" /><br>
 <input value="上传" type="submit" />
</form>
</body>
</html>


--------------------succ.jsp-------------------

<%@ page language="java" contentType="text/html; charset=GBK"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
    <head>
        <title>上传成功</title>
    </head>
    <body>
        上传成功!<br>
    </body>
</html>

包名称:lee

类名称:UploadAction.java

-------------------------------------------------

package lee;

import com.opensymphony.xwork2.Action;
import org.apache.struts2.ServletActionContext;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.opensymphony.xwork2.ActionSupport;

 

public class UploadAction extends ActionSupport
{
 private String title;
    private File[] upload;
    private String[] uploadContentType;
    private String[] uploadFileName;

 //接受依赖注入的属性
    private String savePath;
 //接受依赖注入的方法
    public void setSavePath(String value)
 {
        this.savePath = value;
    }

    private String getSavePath() throws Exception
 {
        return ServletActionContext.getRequest().getRealPath(savePath);
    }
 
 public void setTitle(String title) {
  this.title = title;
 }

 public void setUpload(File[] upload) {
  this.upload = upload;
 }

 public void setUploadContentType(String[] uploadContentType) {
  this.uploadContentType = uploadContentType;
 }

 public void setUploadFileName(String[] uploadFileName) {
  this.uploadFileName = uploadFileName;
 }

 public String getTitle() {
  return (this.title);
 }

 public File[] getUpload() {
  return (this.upload);
 }

 public String[] getUploadContentType() {
  return (this.uploadContentType);
 }

 public String[] getUploadFileName() {
  return (this.uploadFileName);
 }
 @Override
    public String execute() throws Exception
 {
  File[] files = getUpload();
  for (int i = 0 ; i < files.length ; i++)
  {
   
   System.out.println("开始上传图片! ");
   
   //以服务器的文件保存地址和原文件名建立上传文件输出流
   System.out.println("第个"+(i+1)+"图片的大小为:"+getUpload()[i].length());
   FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getUploadFileName()[i]);
   FileInputStream fis = new FileInputStream(files[i]);
   byte[] buffer = new byte[1024];
   int len = 0;
   while ((len = fis.read(buffer)) > 0)
   {
    fos.write(buffer , 0 , len);
   }
   
   System.out.println("上传完毕! ");
   fos.close();
   fis.close();
   String impname = UploadAction.cutImage(getSavePath() + "\\" + getUploadFileName()[i],20, 20);
   
   
   
   //String appPath = ServletActionContext.getRequest().getRealPath("\\"+getSavePath());
   //System.out.println("appPath=========================="+appPath);
   String oldPath = getSavePath() + "\\" + getUploadFileName()[i];
   System.out.println(oldPath);
   File file = new File(oldPath);
   if (file.exists()) {
    if(file.delete()){
     System.out.println("成功删除!");
    }else{
     System.out.println("删除失败!");
    }
    
   } else {
    System.out.println("抱歉不存在! ");
   }
   String[] aa = {oldPath};
  }
  
        return SUCCESS;
    }
 // 图片处理
 public static String cutImage(String srcPath, int width, int height)
   throws IOException {
  File srcFile = new File(srcPath);
  BufferedImage image = ImageIO.read(srcFile);
  int srcWidth = image.getWidth(null);
  int srcHeight = image.getHeight(null);
  int newWidth = 0, newHeight = 0;
  int x = 0, y = 0;
  double scale_w = (double) width / srcWidth;
  double scale_h = (double) height / srcHeight;
  System.out.println("scale_w=" + scale_w + ",scale_h=" + scale_h);
  // 按原比例缩放图片
  if (scale_w < scale_h) {
   newHeight = height;
   newWidth = (int) (srcWidth * scale_h);
   x = (newWidth - width) / 2;
  } else {
   newHeight = (int) (srcHeight * scale_w);
   newWidth = width;
   y = (newHeight - height) / 2;
  }
  BufferedImage newImage = new BufferedImage(newWidth, newHeight,
    BufferedImage.TYPE_INT_RGB);
  newImage.getGraphics().drawImage(
    image
      .getScaledInstance(newWidth, newHeight,
        Image.SCALE_SMOOTH), 0, 0, null);
  // 保存缩放后的图片
  String fileSufix = srcFile.getName().substring(
    srcFile.getName().lastIndexOf(".") + 1);
  String aa = UUID.randomUUID().toString() + "." + fileSufix;
  File destFile = new File(srcFile.getParent(), aa);
  // ImageIO.write(newImage, fileSufix, destFile);
  // 保存裁剪后的图片
  System.out.println("fileSufix====" + fileSufix);

  System.out.println("image=====" + srcPath + aa);
  ImageIO.write(newImage.getSubimage(x, y, width, height), fileSufix,
    destFile);
  return aa;

 }
}

-------------------------struts2配置文件------------------------------

<?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 name="struts.i18n.encoding" value="GBK"/>

 <package name="upload" extends="struts-default">
 
  <action name="upload" class="lee.UploadAction">
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/pjpeg</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"/>   
            <param name="savePath">/upload</param>
   <result name="input">/upload.jsp</result> 
   <result>/succ.jsp</result> 
  </action>
  
 </package>
</struts>

 

------------------------WEB.xml配置-------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <filter>
        <filter-name> struts-cleanup </filter-name>
        <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts-cleanup</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <welcome-file-list>
    <welcome-file>upload.jsp</welcome-file>
  </welcome-file-list>
</web-app>

你可能感兴趣的:(上传图片压缩)