<input type="file" name="files" multiple="multiple">
必须是multiple才可以上传多个文件。
<form id= "uploadForm">
<p >
<input type="text" name="fileIndex" id="fileIndex" />
<input type="text" name="fileSize" id="fileSize" />
上传文件: <input type="file" name="files" id="files" multiple="multiple"> </ p>
<input type="button" value="上传" onclick="doUpload()" />
</form>
<script>
function doUpload() {
var files = document.getElementById("files").files;;
var fileIndex = "";
for(var i = 0; i < files.length; i++){
if(files[i].value != ""){
fileIndex = fileIndex+i+",";
}
}
$("#fileIndex").val(fileIndex.substring(0,fileIndex.length-1));
$("#fileSize").val(files.length); var formData = new FormData($( "#uploadForm" )[0]);
$.ajax({
url: '/uploadFiles.html' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
}
</script>
@Action("/uploadFiles")
public void uploadFiles() throws Exception {
imgsUpload();
}
private File[] files;
private String[] filesFileName; public void setFiles(File[] files) {
this.files = files;
}
public File[] getFiles() {
return files;
} public String[] getFilesFileName() {
return filesFileName;
} public void setFilesFileName(String[] filesFileName) {
this.filesFileName = filesFileName;
} /**
* 上传多图片
* @return 图片路径数组
* @throws IOException if has error
*/
protected String[] imgsUpload() throws IOException {
String fileIndex = paramString("fileIndex");
int fileSize = paramInt("fileSize");
String[] indexs = fileIndex.split(",");
String[] picPath = new String[fileSize];
if (files != null && files[0] != null) {
for (int i = 0; i < files.length; i++) {
if (!ImageUtil.fileIsImage(files[i])) {
printResult("您上传的图片无效,请重新上传!", true);
} else {
int index = Integer.parseInt(indexs[i]);
Operator oper = getOperator();
Date d = DateUtil.getNow();
String upfiesDir = ServletActionContext.getServletContext().getRealPath("/data/upfiles/images/");
String realPath = ServletActionContext.getServletContext().getRealPath("");
String destFileName = upfiesDir + DateUtil.dateStr2(d) + "/" + oper.getId()
+ entityClass.getSimpleName() + "/" + DateUtil.dateStr(d, "HHmmss") + i
+ filesFileName[i].substring(filesFileName[i].lastIndexOf("."));
File imageFile = new File(destFileName);
FileUtils.copyFile(files[i], imageFile);
picPath[index] = destFileName.replace(realPath, "").replace(File.separator, "/");
}
}
}
return picPath;
}
package com.rd.p2p.common.util;

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ImageProducer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import javax.imageio.ImageIO;
import javax.swing.ImageIcon; import org.apache.log4j.Logger; import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiWriter;
import com.sun.jimi.core.options.JPGOptions; /**
* 工具类-图片处理
* */
@SuppressWarnings("restriction")
public class ImageUtil { private static final Logger LOGGER= Logger.getLogger(ImageUtil.class);
private static FileInputStream fis; /**
* 校验文件是否是图片,是:true,否:false
*
* @param file 需要验证的File文件
* @return true or false
*/
@SuppressWarnings("resource")
public static boolean fileIsImage(File file) {
InputStream is = null;
BufferedReader reader = null;
try {
// 将文件转换成输入流
is = new FileInputStream(file);
// 用image IO读取文件,如果文件file不是图片,则为null
BufferedImage image = ImageIO.read(is);
if (image != null) { // 如果image不为空,则说明file文件是图片
reader = new BufferedReader(new FileReader(file));
String exits = null;
while ((exits = reader.readLine()) != null) {
exits = shiftD(exits);
if (exits.indexOf("eval(") > 0 || exits.indexOf("<?php") > 0 || exits.indexOf("eval") > 0) {
return false;
}
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} /**
*
* @param str
* @return
*/
public static String shiftD(String str) {
int size = str.length();
char[] chs = str.toCharArray();
for (int i = 0; i < size; i++) {
if (chs[i] <= 'Z' && chs[i] >= 'A') {
chs[i] = (char) (chs[i] + 32);
}
}
return new String(chs);
} /**
* 将附加图片合并到底图的正中央
*
* @param negativeImagePath 底图路径
* @param addImage 附加图片
* @param toPath 合成图片写入路径
* @throws IOException
*/
public static void mergeBothImageCenter(String negativeImagePath, BufferedImage addImage, String toPath)
throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(negativeImagePath);
BufferedImage image = ImageIO.read(is);
Graphics g = image.getGraphics();
g.drawImage(addImage, image.getWidth() / 2 - addImage.getWidth() / 2,
image.getHeight() / 2 - addImage.getHeight() / 2, null);
os = new FileOutputStream(toPath);
JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(os);
enc.encode(image);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
os.close();
}
if (is != null) {
is.close();
}
}
} /**
* 创建图片放大图(等比放大)
*
* @param src 源图片文件完整路径
* @param dist 目标图片文件完整路径
* @param width 放大的宽度
* @param height 放大的高度
*/
public static void createThumbnail(String src, String dist, int width, int height) {
try {
File srcfile = new File(src);
if (!srcfile.exists()) {
LOGGER.error("文件不存在");
return;
}
BufferedImage image = ImageIO.read(srcfile);
BufferedImage bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bfImage.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null); FileOutputStream os = new FileOutputStream(dist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(bfImage);
os.close();
} catch (Exception e) {
LOGGER.error("创建缩略图发生异常", e);
}
} /**
* 创建图片缩略图(等比缩放)
*
* @param src 源图片文件完整路径
* @param dist 目标图片文件完整路径
* @param width 缩放的宽度
* @param height 缩放的高度
*/
public static void createThumbnailSmall(String src, String dist, float width, float height) {
try {
File srcfile = new File(src);
if (!srcfile.exists()) {
LOGGER.error("文件不存在");
return;
}
BufferedImage image = ImageIO.read(srcfile); // 获得缩放的比例
double ratio = 1.0;
// 判断如果高、宽都不大于设定值,则不处理
if (image.getHeight() > height || image.getWidth() > width) {
if (image.getHeight() > image.getWidth()) {
ratio = height / image.getHeight();
} else {
ratio = width / image.getWidth();
}
}
// 计算新的图面宽度和高度
int newWidth = (int) (image.getWidth() * ratio);
int newHeight = (int) (image.getHeight() * ratio); BufferedImage bfImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
bfImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0,
null); FileOutputStream os = new FileOutputStream(dist);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(bfImage);
os.close();
} catch (Exception e) {
LOGGER.error("创建缩略图发生异常", e);
}
} /**
* 防止处理图片变色
*
* @param image
* @return
*/
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
} image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {// linux没有专门处理图片的图形界面,但是不会影响正常的图片处理。此处不用补货异常
} if (bimage == null) {
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
} Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
} /**
* 添加图片水印,添加完成之后,默认覆盖原有图片,另,在对图片处理时,要防止图片变色
*
* @param targetImg 目标图片路径
* @param waterImg 水印图片路径
* @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public final static void pressImage(String targetImg, String waterImg, String imageType, int x, int y, float alpha) {
try {
File file = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null); Image waterImage = ImageIO.read(new File(waterImg)); // 水印文件
int width_1 = waterImage.getWidth(null);
int height_1 = waterImage.getHeight(null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); int widthDiff = width - width_1;
int heightDiff = height - height_1;
if (x < 0) {
x = widthDiff / 2;
} else if (x > widthDiff) {
x = widthDiff;
}
if (y < 0) {
y = heightDiff / 2;
} else if (y > heightDiff) {
y = heightDiff;
}
g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
g.dispose();
ImageIO.write(bufferedImage, imageType, file);
} catch (IOException e) {
e.printStackTrace();
}
} /**
* @param source
* @param dest
* @param quality 图片质量,最好不要设置为100 。 0<quality<100 图片格式转换
*/
public static void toJpg(String source, int quality) {
// 0<quality<100
if (quality < 0 || quality > 100 || (quality + "") == null || (quality + "").equals("")) {// 图片质量,如果为空,则默认为75
quality = 75;
} String outfile = getFileName(source) + getFileTypeOne(source);
try {
JPGOptions options = new JPGOptions();
options.setQuality(quality);
ImageProducer image = Jimi.getImageProducer(source);
JimiWriter writer = Jimi.createJimiWriter(outfile);
writer.setSource(image);
// 加入属性设置,非必要
// /*
writer.setOptions(options);
// */
writer.putImage(outfile);
} catch (Exception je) {
je.printStackTrace();
}
} /**
* 上传文件名称
*
* @param file
* @return
*/
public static String getFileName(String file) {
return file.substring(0, file.lastIndexOf("."));
} /**
* 提取上传文件类型名。如23424234.gif,返回".gif"
*
* @param file
* @return
*/
public static String getFileTypeOne(String file) {
return file.substring(file.lastIndexOf("."));
} /**
* 提取上传文件类型名。如23424234.gif,返回"gif"
*
* @param file
* @return
*/
public static String getFileTypeTwo(String file) {
return file.substring(file.lastIndexOf(".") + 1);
} /**
* 获取文件大小
* @param filePath
*/
public static int getFileByte(File file){
try{
fis = new FileInputStream(file);
try{
return fis.available();
}catch(IOException e1){
e1.printStackTrace();
}
}catch(FileNotFoundException e2){
e2.printStackTrace();
}
return 0;
}
}

struts2 input file多文件同时通过ajax提交的更多相关文章

  1. 通过Ajax方式上传文件(input file),使用FormData进行Ajax请求

    <script type="text/jscript"> $(function () { $("#btn_uploadimg").click(fun ...

  2. 动态input file多文件上传到后台没反应的解决方法!!!

    其实我也不太清除具体是什么原因,但是后面就可以了!!! 我用的是springMVC 自带的文件上传 1.首先肯定是要有springMVC上传文件的相关配置! 2.前端 这是动态input file上传 ...

  3. html,图片上传预览,input file获取文件等相关操作

    input file常用方法: var obj=document.getElementById("upimage"); var file=obj.files[0];//获取文件数据 ...

  4. html input file 设置文件类型

    解决方案: 使用 input 的 accept 属性指定接受文件类型 -----------更新--------------- 之前的代码有个缺点,打开文件窗口时会自动筛选文件夹下所有符合设定类型的文 ...

  5. IE10 解决input file 同一文件不触发onchange事件

    if (window.ActiveXObject) { var reg = /10\.0/; var str = navigator.userAgent; if (reg.test(str)) { v ...

  6. jspsmartupload 文件上传让input数据和文件上传同时提交

    一.使用原因: 文件上传时,表单的属性中必须要有multipart/form-data,如以下例子: <form name="form_post" class="a ...

  7. input:file onchange事件无法读取解决方法

    最近做项目,移动端的多文件上传,使用input:file读取文件 <input type='file' name='file' multiple accept='image/*' capture ...

  8. ajax提交表单向后台发送数据

    Ajax提交表单 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  9. form表单提交数据,页面必定会刷新,ajax提交数据不会刷新,做到悄悄提交,多选删除,ajax提交实例

    很多页面用到的模态对话框,如知明网站https://dig.chouti.com/的登录页都是模态对话框, 当点登录时,是用的ajax提交,因为输入错了信息,有返回消息,而页面没有刷新. jquery ...

随机推荐

  1. nginx 安全配置文档

    1.配置文档中有多处明确写出了nginx的配置文件路径,该路径是测试环境中的路径,线上系统的nginx配置文件与文档中所写的路径可能不一样,在进行相关配置时,应以线上配置文件的实际路径为准. 线上系统 ...

  2. fgetpos, fseek, fsetpos, ftell, rewind - 重定位某个流

    总览 (SYNOPSIS) #include <stdio.h> int fseek(FILE *stream, long offset, int whence); long ftell( ...

  3. python_使用qrcode生成二维码

    1.功能 使用qrcode生成二维码 2.代码 #生成二维码: import qrcode #根据url生成二维码 def qrcodeWithUrl(url): img = qrcode.make( ...

  4. luogu 1608 路径统计--最短路计数

    https://www.luogu.org/problemnew/show/P1608 题意https://www.cnblogs.com/rmy020718/p/9440588.html相似,建议还 ...

  5. UVa-1339-古老的密码

    这题的话,我们可以把字符串序列里面的字母直接计数,然后比较两个数组里面的数字是否一一相同,然后就可以直接判定YES or NO. 因为它题目中说的就是一种映射的关系,首先我们读入之后,把两个字符串的不 ...

  6. (10) openssl dhparam(密钥交换)

    openssl dhparam用于生成和管理dh文件.dh(Diffie-Hellman)是著名的密钥交换协议,或称为密钥协商协议,它可以保证通信双方安全地交换密钥. 但注意,它不是加密算法,所以不提 ...

  7. 给Django中的url起名字

    url反转  =>reverse 1.from django.shortcuts  import  reverse 2. 利用reverse函数对URL名称进行反转  reverse(url名称 ...

  8. STM32定时器的两个小难点

    TIM1 TIM8 挂在APB2上 一般为72M 也即APB2分频系数为1其余TIMER可以认为都挂在APB1上,一般为36M 也即APB1分频系数为2 或者更大 至少为2 APB1不能超过36M定时 ...

  9. 【C#】【数据结构】005-栈:顺序栈

    C#数据结构:顺序栈 1.自定义顺序栈结构: /// <summary> /// 顺序栈 /// </summary> /// <typeparam name=" ...

  10. JavaScript中变量、作用域和内存问题(JavaScript高级程序设计第4章)

    一.变量 (1)ECMAScript变量肯能包含两种不同的数据类型的值:基本类型值和引用类型值.基本类型值指的是简单的数据段,引用类型值指那些可能由多个值构成的对象. (2)基本数据类型是按值访问,可 ...