081102 struts2 + swfupload 批量上传图片

2024-04-14 15:38

本文主要是介绍081102 struts2 + swfupload 批量上传图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

upload.jsp:
在这个文件里,使用了新swfload的上传方式,将文件流发送到struts2的doMultipleUploadUsingList.action,uploadStart的这个function,是将页面上的"id"元素的值一起带过去,上传过程中,会在divStatus的DIV中显示上传进度条。

<%@ page  contentType="text/html;  charset=utf-8"%>
<html>
<head>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     <link href="<%=request.getContextPath() %>/admin/uploadpic/js/default.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="<%=request.getContextPath() %>/admin/uploadpic/js/swfupload.js"></script>
 <script type="text/javascript" src="<%=request.getContextPath() %>/admin/uploadpic/js/handlers.js"></script>
 <script type="text/javascript" src="<%=request.getContextPath() %>/admin/uploadpic/js/fileprogress.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath() %>/admin/uploadpic/js/swfupload.queue.js"></script>
 <script type="text/javascript">
  var swfu;
  window.onload = function () { 
   var settings = {
    // Backend Settings
    file_post_name : "upload",
    upload_url: "<%=request.getContextPath() %>/admin/product/doMultipleUploadUsingList.action", // Relative to the SWF file
    post_params: {"product1": "1"},        
          use_query_string:false,
    // File Upload Settings
    file_size_limit : "100 MB",
    file_types : "*.*",
    file_types_description : "All Files",
    file_upload_limit : 100,
    file_queue_limit : 0,
    custom_settings : {
     progressTarget : "fsUploadProgress",
     cancelButtonId : "btnCancel"
    },
    debug: false,

    // The event handler functions are defined in handlers.js
    file_queued_handler : fileQueued,
    file_queue_error_handler : fileQueueError,
    file_dialog_complete_handler : fileDialogComplete,
    upload_start_handler : uploadStart,
    upload_progress_handler : uploadProgress,
    upload_error_handler : uploadError,
    upload_success_handler : uploadSuccess,
    upload_complete_handler : uploadComplete,
    queue_complete_handler : queueComplete,
    // Flash Settings
    flash_url : "<%=request.getContextPath() %>/admin/uploadpic/js/swfupload_f8.swf" // Relative to this file
    
   };
   swfu = new SWFUpload(settings);
  }
   function uploadStart(file) {
   document.getElementById("back").innerHTML='';
   var post_params = this.settings.post_params;
   post_params.id = document.getElementById("id").value;
   this.setPostParams(post_params);
   return true;
   }           
   <style type="text/css">
   #content button,input,span{
   margin: 5 5 5 5;
   }
   #back{
   width:810;
   height:500;
   float:left;
   text-align:center;
   vertical-align:middle;
   overflow:auto;
   }
   #img2{
   float:left;
   margin: 1 1 1 1;
   text-align:center;
   vertical-align:middle;
   display: table-cell;
   display: block;
   font-size: 68px;
   width:78;
   height:78;
   border: 1px solid #B10000;
   }
   #img2 img{
   vertical-align:middle;
   cursor: pointer;
   }
   #img2 img hover{
   cursor: pointer;
   }  
</style>
</head>
  <div id="SWFUploadTarget" >
<body>

<div id="content">
  <span>1、Product ID</span><input type="text" name="id" id="id" value= <%=request.getParameter("id") %> readonly>
  <button id="btnBrowse" type="button" style="padding: 6px;" onClick="swfu.selectFiles(); this.blur();javascript:document.getElementById('divStatus').innerHTML='';">
  </div>
 </div>
    <p>
   <fieldset class="flash" id="fsUploadProgress">
   <legend>Upload Progress</legend>
   </fieldset>
  <div id="divStatus"></div>
   <div>
    <input id="btnCancel" type="button" value="Cancel All Upload" onClick="swfu.cancelQueue();" disabled="disabled" style="font-size: 8pt;" />

   </div>

<div id="back"></div>
</body>
<html>

MultipleFileUploadUsingListAction是一个可以通用的struts2 action,可以接收批量或单个上传过来的图片。并且可以选择生成相应压缩图。图片生成的命名方式是从xxx_01、xxx_02、xxx_03一直自动排列下去。压缩图为xxx_01_70

package com..web.action;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.web.commons.util.DirList;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("serial")
public class MultipleFileUploadUsingListAction extends ActionSupport {

    private String id;
    private File[] uploads;
    private String[] uploadFileNames;
    private String[] uploadContentTypes;
   
    public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public File[] getUpload() { return this.uploads; }
    public void setUpload(File[] upload) { this.uploads = upload; }

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

    public String[] getUploadContentType() { return this.uploadContentTypes; }
    public void setUploadContentType(String[] uploadContentType) { this.uploadContentTypes = uploadContentType; }   
 
  public String upload() throws Exception{
   try{
  String productname=id;
  String url = ServletActionContext.getServletContext().getRealPath("Personalizedphoto")+"\\"+id+"\\";
   for (int i=0;i<uploads.length;i++) {
  FileInputStream fis=new FileInputStream(uploads[i]); 
    if(!(new File(url).isDirectory())) 
    { 
    new File(url).mkdir();  
    }
   int temp=1,temp2=1;
   String myFileName = productname+"_0"+temp;
   DirList dirlist = new DirList();
   String[] dir =dirlist.list(url);  
   for(int j=0;j<dir.length;j++){
      String[] split = dir[j].split("\\.");
          if(split[1].equals("jpg")&&split[0].split("\\_").length==3){  
          String[] split2=split[0].split("\\_");
       if(Integer.parseInt(split2[1])>0&Integer.parseInt(split2[1])>=temp2){
       temp2=Integer.parseInt(split2[1])+1;
       }
       if(Integer.parseInt(split2[1])==0){
       temp2=1;
       }
          }
    } 
    if(temp2<10){
    myFileName = productname+"_0"+temp2;
    }else{
    myFileName = productname+"_"+temp2;
    }
    
    FileOutputStream fos=new FileOutputStream(url+myFileName+"_800.jpg");  
  byte[] buffer=new byte[1024];
     int len=0;
     while((len=fis.read(buffer))>0){
         fos.write(buffer, 0, len);
     }

     java.io.File file = new java.io.File(url+myFileName+"_800.jpg");
     String newurl=url+myFileName+"_70.jpg";  
     java.awt.Image src = javax.imageio.ImageIO.read(new java.io.File(url+myFileName+"_800.jpg"));
    
     float tagsize=70;
     int old_w=src.getWidth(null);                             
     int old_h=src.getHeight(null);
     int new_w=0;
     int new_h=0;                           
     float tempdouble;
     if(old_w>old_h){
      tempdouble=old_w/tagsize;
     }else{
      tempdouble=old_h/tagsize;
     }
     new_w=Math.round(old_w/tempdouble);
     new_h=Math.round(old_h/tempdouble);     java.awt.image.BufferedImage tag = new java.awt.image.BufferedImage(new_w,new_h,java.awt.image.BufferedImage.TYPE_INT_RGB); 
     tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);   
     FileOutputStream newimage=new FileOutputStream(newurl);         
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);      
     encoder.encode(tag);                                               
     newurl=url+myFileName+"_130.jpg";  
     tagsize=130;
     if(old_w>old_h){
      tempdouble=old_w/tagsize;
     }else{
      tempdouble=old_h/tagsize;
     }
     new_w=Math.round(old_w/tempdouble);
     new_h=Math.round(old_h/tempdouble);
     tag = new java.awt.image.BufferedImage(new_w,new_h,java.awt.image.BufferedImage.TYPE_INT_RGB);
     tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);
     newimage=new FileOutputStream(newurl);          
     encoder = JPEGCodec.createJPEGEncoder(newimage);      
     encoder.encode(tag); 
     newurl=url+myFileName+"_180.jpg";  
     tagsize=180;
     if(old_w>old_h){
      tempdouble=old_w/tagsize;
     }else{
      tempdouble=old_h/tagsize;
     }
     new_w=Math.round(old_w/tempdouble);
     new_h=Math.round(old_h/tempdouble);
     tag = new java.awt.image.BufferedImage(new_w,new_h,java.awt.image.BufferedImage.TYPE_INT_RGB);
     tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);
     newimage=new FileOutputStream(newurl);         
     encoder = JPEGCodec.createJPEGEncoder(newimage);      
     encoder.encode(tag);                                               
     newurl=url+myFileName+"_500.jpg";  
     tagsize=500;
     if(old_w>old_h){
      tempdouble=old_w/tagsize;
     }else{
      tempdouble=old_h/tagsize;
     }
     new_w=Math.round(old_w/tempdouble);
     new_h=Math.round(old_h/tempdouble);
     tag = new java.awt.image.BufferedImage(new_w,new_h,java.awt.image.BufferedImage.TYPE_INT_RGB);
     tag.getGraphics().drawImage(src,0,0,new_w,new_h,null);
     newimage=new FileOutputStream(newurl);          
     encoder = JPEGCodec.createJPEGEncoder(newimage);      
     encoder.encode(tag);  
     newimage.close();
   } 
   }catch(Exception e){}
   this.setId(id);
   return SUCCESS;
 }
    
 }


这个action还调用了一个类DirList ,是用于扫描当前文件夹里的图片,并且根据当前的命名情况来命名新上传的图片,如原来已经有了10张,那上传之后的就从第11开始命名。

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Pattern;
public class DirList {
 public String[] list(String thepath) {
  File path = new File(thepath); 
  String[] list;  
  list = path.list();
  Arrays.sort(list, new AlphabeticComparator());
  return list;
 }
 
 private void deleteFile(File file){
  if(file.exists()){
  if(file.isFile()){
  file.delete();
  }else if(file.isDirectory()){
  File files[] = file.listFiles();
  for(int i=0;i<files.length;i++){
  this.deleteFile(files[i]);
  }
  }
  file.delete();
  }else{
  }
  }
}

class DirFilter implements FilenameFilter { 
 private Pattern pattern;  public DirFilter(String regex) {
  pattern = Pattern.compile(regex);  }
 public boolean accept(File dir, String name) {  
  // Strip path information, search for regex:  
  return pattern.matcher(new File(name).getName()).matches();
  }
 }

class AlphabeticComparator implements Comparator {
 public int compare(Object o1, Object o2) {  
  String s1 = (String) o1;    String s2 = (String) o2;   
  return s1.toLowerCase().compareTo(s2.toLowerCase()); 
  }
 }


 

这篇关于081102 struts2 + swfupload 批量上传图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/903374

相关文章

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意

c/c++的opencv实现图片膨胀

《c/c++的opencv实现图片膨胀》图像膨胀是形态学操作,通过结构元素扩张亮区填充孔洞、连接断开部分、加粗物体,OpenCV的cv::dilate函数实现该操作,本文就来介绍一下opencv图片... 目录什么是图像膨胀?结构元素 (KerChina编程nel)OpenCV 中的 cv::dilate() 函

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

GitLab文件的上传与下载方式

《GitLab文件的上传与下载方式》:本文主要介绍GitLab文件的上传与下载方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录GitLab 项目拉取到本地GitLab 项目上传方法方法 1:本地项目未初始化Git方法 2:本地项目已初始化GitGitLab 上

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

MySQL数据库实现批量表分区完整示例

《MySQL数据库实现批量表分区完整示例》通俗地讲表分区是将一大表,根据条件分割成若干个小表,:本文主要介绍MySQL数据库实现批量表分区的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录一、表分区条件二、常规表和分区表的区别三、表分区的创建四、将既有表转换分区表脚本五、批量转换表为分区

Nginx 413修改上传文件大小限制的方法详解

《Nginx413修改上传文件大小限制的方法详解》在使用Nginx作为Web服务器时,有时会遇到客户端尝试上传大文件时返回​​413RequestEntityTooLarge​​... 目录1. 理解 ​​413 Request Entity Too Large​​ 错误2. 修改 Nginx 配置2.1