前言:
案例使用的开发工具:eclipse
不足之处希望各位大佬们多多指教( ̄▽ ̄*)顶
1. jar包
2. js文件
<link rel="stylesheet" type="text/css" href="js/webuploader-0.1.5/webuploader.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/webuploader-0.1.5/webuploader.min.js"></script>
<script type="text/javascript" src="js/layer/layer.js"></script>
3. HTML代码
<form id="myForm" enctype="multipart/form-data">
<label>图片路径:</label><br>
<span id="picker">选择图片</span>
<span id="showImage"></span>
<input class="form-control" type="hidden" name="content_imgUrl" value=""/>
</form>
4. js代码
<script type="text/javascript">
//图片上传
var uploader = WebUploader.create({
auto: true,// 选完文件后,是否自动上传。
swf: 'js/webuploader-0.1.5/Uploader.swf',// swf文件路径
server: 'webUploader.do' ,// 文件接收服务端。
pick: '#picker',//内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
method: 'POST', // 文件上传方式,POST或者GET。
fileVal:'uploadfile', // [默认值:'file'] 设置文件上传域的name。
accept: { // 只允许选择图片文件。
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
//获取图片路径
uploader.on( 'uploadSuccess', function( file,response) {
if(response.code ==200){
layer.msg("图片上传成功!");
$("#showImage").empty();
$("#showImage").append("<img style='width:100px;height:100px;' src='"+response.data+"' />");
$("input[name='content_imgUrl']").val(response.data);
}else{
layer.msg(response.data);
}
});
var loading;
//开始上传是时触发
uploader.on('startUpload',function(){
loading = layer.load(1, { //显示loading
shade: [0.5,'#000'], //0.1透明度的白色背景
});
})
//上传结束
uploader.on('uploadFinished',function(){
layer.close(loading ); //关闭loading
})
</script>
5. XML配置
5.1 web.xml
<servlet>
<description></description>
<display-name>WebUploaderServlet</display-name>
<servlet-name>WebUploaderServlet</servlet-name>
<servlet-class>servlet.WebUploaderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WebUploaderServlet</servlet-name>
<url-pattern>/webUploader.do</url-pattern>
</servlet-mapping>
5.2 Tomcat下的server.xml的<Host></Host>标签中添加<Content />
<Context docBase="D:\upload" path="/upload" reloadable="true" />
6. java代码
6.1 servlet:WebUploaderServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String,Object> map=WebUploaderAction.webUploaderImg(request, response);
System.out.println("code:"+map.get("code")+" data:"+map.get("data"));
try {
response.getWriter().write(JSONObject.fromObject(map).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
6.2 class:WebUploaderAction.java
package action;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class WebUploaderAction extends HttpServlet{
// 上传文件存储目录
private static final String UPLOAD_DIRECTORY = "upload";
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
public static Map<String,Object> webUploaderImg(HttpServletRequest request,HttpServletResponse response) {
System.out.println("webUploaderImg方法进入");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json");
Map<String,Object> map=new HashMap<String,Object>();
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
map.put("code", 400);
map.put("data", "Error: 表单必须包含 enctype=multipart/form-data");
return map;
}
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件上传值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文处理
upload.setHeaderEncoding("UTF-8");
// 构造临时路径来存储上传的文件
// 这个路径相对当前应用的目录
String uploadPath = "D:/" + UPLOAD_DIRECTORY;
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
//设置路径参数
String imgUrl="";
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
System.out.println("c");
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
//获取上传文件的名称
String fileName =UUID.randomUUID().toString()+".png";//防重名
//指定的类型
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制台输出文件的上传路径
System.out.println("文件上传成功:"+filePath);
// 保存文件到硬盘
item.write(storeFile);
imgUrl="/" + UPLOAD_DIRECTORY + "/" + fileName;//不可以直接filePath
System.out.println("imgUrl:"+imgUrl);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
map.put("code",200);
map.put("data", imgUrl);
return map;
}
}
7. 效果展示