一、无刷新文件上传代码实现:
引用资源文件:
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/ajaxfileupload.js"></script>
二、实现代码:
<div style="background: #ff9c01; color: #FFF; font-size: 14px; font-family: Microsoft YaHei; padding: 3px 6px; margin-left: 8px;width: 80px;text-align: center;">
<a href="javascript:void(0);" οnclick="tempUpLoadFile('pth','naPt','naSh','png,jpg');">上传文件</a>
</div>
<span id="naSh"></span>
<input type="hidden" id="pth"/>
<input type="hidden" id="naPt"/>
<jsp:include page="/WEB-INF/jsp/common/uploadTemp.jsp"/>
三、uploadTemp.jsp 实现代码:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<script type="text/javascript">
/* js/ajaxfileupload.js */
/**
* 上传文件控件
* filePath :input 保存上传到服务器文件的路径
* fileName :input 保存文件名称
* fileNameShow :span 要显示上传文件的名称
* checkFileType : 要上传文件的类型,逗号分隔
*/
var path,name,nameShow,chckFiName;
function tempUpLoadFile(filePath,fileName,fileNameShow,checkFileType) {
path = filePath;
name = fileName;
chckFiName = checkFileType;
if(fileNameShow != undefined){
nameShow = fileNameShow;
}
$("#fileTempId").val();
$("#fileTempId").click();
}
/**
* JS 上传回调函数,可重写
*/
function callBackJs(filePath,fileName){
$("#"+path).val(filePath);
$("#"+name).val(fileName);
$("#"+nameShow).text(fileName);
}
function checkUploadFileType(){
//上传文件全路径
var filepath = $("#fileTempId").val();
var dotIndex = filepath.lastIndexOf(".");
//文件没有后缀时,进行提示
if (-1 == dotIndex){
alert('格式仅限于' + chckFiName + ', 请重新选择。');
return false;
}
var suffix = filepath.substring(dotIndex+1, filepath.length).toLowerCase(); //文件后缀
var chckFiNames = chckFiName.split(",");
var isLegal = false;
for (var i = 0; i < chckFiNames.length; i++){
if (suffix == chckFiNames[i]){
isLegal = true;
break;
}
}
if(!isLegal){
alert('文件格式仅限于' + chckFiName + ', 请重新选择。');
return false;
}
return true;
}
function fileSubmit() {
if(checkUploadFileType()){
$.ajaxFileUpload({
url : '<%=basePath%>file/uploadImage.do', //用于文件上传的服务器端请求地址
type:'post',
async : true,
secureuri : false, //是否启用安全提交一般设置为false
fileElementId : 'fileTempId', //文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType : 'json', //返回值类型 一般设置为xml,script,json,html
success : function(data, status) {
if(data.success == 'success'){
callBackJs(data.msg,data.fileName);
}else{
alert("上传文件出错啦!"+e);
}
},error:function(data, status, e){
alert("网络连接错误!"+e);
}
});
}
}
</script>
<span id="showProcess"></span>
<input style="display: none" type="file" id="fileTempId" name="file" οnchange="fileSubmit()"/>
三、后台代码实现:
package com.company.common.baseAction;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Title FileUntilAction.java
* Description 文件工具操作类
* Author XXXX
* Date 2016-2-25 下午02:47:23
* Version V1.0
*/
@Controller
@RequestMapping("/file")
public class FileUntilAction {
@ResponseBody
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public Map<String,Object> loginEnhome(HttpServletRequest request, HttpServletResponse response) {
System.out.println("上传文件开始。。。。。。。");
InputStream is = null;
Socket socket = null;
OutputStream os = null;
InputStream sis = null;
String path = "";
Map<String, Object> content = new HashMap<String, Object>();
try {
String serverIp = "127.0.0.1";
int port = 8457 ;
if (serverIp.equals("")) {
content.put("success", false);
content.put("msg", "没有配置图片服务器IP!");
return content;
}
DiskFileItemFactory dff = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(dff);
List<FileItem> fileItems = fileUpload.parseRequest(request);
if (fileItems.size()==0) {
System.out.println("没有文件上传!");
content.put("success", false);
content.put("msg", "没有文件上传!");
return content;
}
// 获取图片参数
is = fileItems.get(0).getInputStream();
long size = is.available();
String fileName = fileItems.get(0).getName();
String fileType= fileName.substring(fileName.indexOf(".")+1, fileName.length());
String uploadName = fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length());
// 请求参数
StringBuffer params = new StringBuffer();
params.append("cmd:upload\r\n");
params.append("name:" + 88 + "_" + 88 + "\r\n");
params.append("type:" + fileType +"\r\n");
params.append("size:" + size + "\r\n");
params.append("\r\r\n");
// 发起SOCKET请求
socket = new Socket(serverIp, port);
os = socket.getOutputStream();
os.write(params.toString().getBytes("GBK"));
os.flush();
sis = socket.getInputStream();
byte[] result = new byte[10240];
sis.read(result, 0, 1024);
System.out.println("首次:" + IOUtils.toString(result, "UTF-8"));
// 上传文件
byte[] data = new byte[10240];
int read = 0;
while ((read = is.read(data)) != -1) {
os.write(data, 0, read);
}
socket.shutdownOutput();
// 解析请求结果
sis.read(result, 0, 1024);
String uploadResult = IOUtils.toString(result, "UTF-8");
System.out.println("第二次:" + uploadResult);
String[] uplpads = uploadResult.split("\r\n");
for (String r : uplpads) {
if (r.contains("path")) {
path = r.replace("path:", "").replaceAll("\\r", "").replaceAll("\\n", "").trim();
}
}
content.put("success", "success");
content.put("msg", path);
content.put("fileName",uploadName);
}
catch (Exception e) {
System.out.println("上传文件失败!!"+e);
content.put("success", "fail");
content.put("msg", "图片上传失败!");
}
finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(sis);
try {
socket.close();
}
catch (IOException e) {
System.out.println("Socket关闭失败!"+ e);
}
}
System.out.println("content:"+content);
return content;
}
}
点击上传按钮图标后,直接弹出上传框,选择文件后,后台直接上传,并在前台显示上传文件名称:
注意:后台使用的是ServletFileUpload 方法,在使用springMVC 或 struts 时,一定要删除或重写ServletFileUpload 中的上传方法, 否则因为 fileUpload.parseRequest(request) 方法获取不到上传文件,因为在源码ServletFileUpload 中已经存在此方法,有重复出现。
解决办法1,删除配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
方法2,重写此方法
运用ajaxUploadFile上传,有点不好,无法获取上传进度信息,重写方法后,设置文件监听可获取进度,此处待后期更新