在写项目的时候,经常用到图片上传啊什么的,这儿提供一个方法,万能,咋都能用。
ajax
$(".save-head").click(function () {
var formData = new FormData();
formData.append('file', $('#upload')[0].files[0]);
formData.append('school', '${userCenterJson.teacher.schoolCode }');
formData.append('teacherCode', '${userCenterJson.teacher.teacherCode }');
$.ajax({
url : '<%=SignAndMd5.uploadimg %>',
scriptCharset : "UTF-8",
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
type : 'POST',
cache : false,
data : formData,
processData : false,
contentType : false,
}).done(function(data) {
alert("上载成功");
$("#headImg").val(data.trim());
$("#headform").submit();
}).fail(function(res) {
console.log(res.responseText);
});
});
这边对formData做一个解释,其实这就是一个载体,有点像json一样,用来传数据的,但是他可以放着文件信息传到后台
我这边传了两个值,用于动态拼装文件路径,后台获取的代码这里放一下:
String school = "";
String teacherCode = "";
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
item.getString("UTF-8");
if (item.getFieldName().equals("school")) {
school = item.getString();
filePath += school + "//";
filePath += "TeacherHeadPic//";
}
if (item.getFieldName().equals("teacherCode")) {
teacherCode = item.getString();
}
}
我的ajax url为了方便直接是一个jsp,随取随用。
<%@page import="java.awt.Color"%>
<%@page import="com.kids.image.ImageUtils"%>
<%@page import="com.kids.picWork.ImgHandel"%>
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage=""%>
<%@ page import="java.util.List"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%
request.setCharacterEncoding("UTF-8");
String filePath = request.getRealPath("/SchoolCenter/") + "//";
try {
DiskFileItemFactory fu = new DiskFileItemFactory();
fu.setSizeThreshold(2 * 1024 * 1024);
fu.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(fu);
upload.setHeaderEncoding("UTF-8");
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
String TextDate = "";
String school = "";
String teacherCode = "";
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
item.getString("UTF-8");
if (item.getFieldName().equals("school")) {
school = item.getString();
filePath += school + "//";
filePath += "TeacherHeadPic//";
}
if (item.getFieldName().equals("teacherCode")) {
teacherCode = item.getString();
}
}
Iterator iter2 = fileItems.iterator();
while (iter2.hasNext()) {
FileItem item = (FileItem) iter2.next();
item.getString("UTF-8");
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name1 = item.getName();//获取上传的文件名
long size = item.getSize();//获取上传的文件大小(字节为单位)
if ((name1 == null || name1.equals("")) && size == 0) {
continue;//跳到while检查条件
}
int end = name1.length();
int begin = name1.lastIndexOf("\\");
String newname = name1.substring(begin + 1, end);
TextDate = newname;
if (TextDate.length() == 0) {
System.out.println("上传文件导入异常,请重新上传...");
} else {
try {
//保存文件
newname = teacherCode + "." + newname.split("\\.")[1];
System.out.println(newname);
File savedFile = new File(filePath, newname);//用原文件名,作为上传文件的文件名。
item.write(savedFile);
item.delete();
new ImgHandel().thumbnailImage(filePath + newname, 150, 150, "thumb_", false);
File f = new File(filePath + newname);
ImageUtils.fromFile(f)
.scale(1)
.rotate(90) //旋转角度
.quality(1)
.bgcolor(Color.white)
.toFile(new File(filePath + newname));
out.println(newname);
out.flush();
out = pageContext.pushBody();
} catch (Exception e) {
out.println(e);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
这里的ajax对图片有两个处理,
一个是生成缩略图,
new ImgHandel().thumbnailImage(filePath + newname, 150, 150, "thumb_", false);
一个是旋转上传的图片
new ImgHandel().thumbnailImage(filePath + newname, 150, 150, "thumb_", false);
File f = new File(filePath + newname);
ImageUtils.fromFile(f)
.scale(1)
.rotate(90) //旋转角度
.quality(1)
.bgcolor(Color.white)
.toFile(new File(filePath + newname));
如果不需要,直接删除即可。
这两个操作在另外文章中。