您的位置:首页 > 编程语言 > Java开发

SpringMVC结合ajaxfileupload.js实现异步上传文件

2016-07-18 15:07 1006 查看
相比较提交表单实现文件上传,使用ajaxfileupload.js实现异步上传显得更加灵活。

下载ajaxfileupload.js并在页面中引用,jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="${ctx }/static/scripts/ajaxfileupload.js"></script>
<style>
.filebtn{
opacity:0;
filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0); /* IE6/IE7/8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"; /*  IE8 */
width:70px;
position:absolute;
top:0;
left:0
}
</style>
</head>
<body>
<div>
<!--这里实现了兼容ie8下的文件上传,同时保持设计的样式-->
<span style="position:relative">
<input type="button" class="table-btn" value="选择文件" />
<input type="file" name='file' id='file' class="filebtn"/>
</span>
<input id="upfile" type="button" value="上传" class="table-btn" onclick="uploadPlanPic()" />
</div>
</body>
<script>
//上传文件
        function uploadPlanPic() {
          var filepath=$("#file").val();
          if(filepath ==""){
            alert("请选择图片进行上传!");
            return; 
          }
          var extStart=filepath.lastIndexOf("."); 
          var ext=filepath.substring(extStart,filepath.length).toUpperCase(); 
          if(ext!='JPG'||ext!='GIF'||ext!='PNG'||ext!='BMP'){
alert('上传图片格式仅限于.jpg .gif .png .bmp');
            return;
          }
            $.ajaxFileUpload
            (
                {
                    url:'${ctx}/zxlr/ghxx/uploadPlanpicFile', //用于文件上传的服务器端请求地址
                    secureuri: false, //一般设置为false
                    fileElementId: 'file', //文件上传控件的id属性
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        if (typeof (data.result) != 'undefined') {
                                if(data.result == "success")
                                {
                                  alert("文件上传成功!");
                                }else{  
                                  if(data.msg == "error1"){
                                    alert("上传失败,请上传小于10M的文件!");
                                  }else if(data.msg == "error3"){
                                alert("该文件名已经被使用");
                                  }else{
                                    alert("文件上传失败,请重新上传!");
                                  }
                                
                                }
                        }
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert("文件上传失败,请重新上传!");
                    }
                }
            )
        }
</script>
</html>

服务器端代码:

@RequestMapping("/ghxx/uploadPlanpicFile")
public String uploadContFile(HttpServletRequest request, HttpServletResponse response){
final String message = "";

try {
final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
final MultipartFile myfile = multiRequest.getFile("file");
final InputStream stream = myfile.getInputStream();
final InputStream stream2 = myfile.getInputStream();
final String vm = UploadUtil.validateImg(myfile, stream);

if (!"success".equals(vm)) {
UploadUtil.writeToPage(vm, response);
return null;
}

final String filename = myfile.getOriginalFilename();
//final String newfileName = UploadUtil.getOrderNum() + filename.substring(filename.lastIndexOf('.'));

// 这里是物理路径,在实际环境中将配置虚拟路径
final String filePath = UploadUtil.getPropertieValue("param.properties", "uploadPlanpic.path");

StringUtil.checkDir(filePath);

File file =new File(filePath +File.separator+ filename);
String isExist = UploadUtil.validateExistOrNo(file);
if (!"success".equals(isExist)) {
UploadUtil.writeToPage(isExist, response);
return null;
}
OutputStream bos = new FileOutputStream(file);

int bytesRead = 0;
final byte[] buffer = new byte[8192];
while ((bytesRead = stream2.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// 将文件写入服务器
}
bos.close();
stream2.close();
stream.close();
UploadUtil.writeToPage(UploadUtil.makeJsonResponse(true, filename), response);
return null;

} catch (final FileNotFoundException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
UploadUtil.writeToPage(UploadUtil.makeJsonResponse(false, message), response);
return null;
}


UploadUtil类:

package com.jusfoun.estate.util.common;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
*上传文件工具类
* @author bukai
*
*/
public class UploadUtil {

/**
* 拼接json
* @param result
* @param message
* @return
*/
public static String makeJsonResponse(boolean result, String message) {
if (result) {
return "{\"result\":\"success\",\"msg\":\"" + message + "\"}";
}
return "{\"result\":\"faild\",\"msg\":\"" + message + "\"}";
}

/**
*ajax打印到前台
* @param content
* @param response
*/
public static void writeToPage(String content, HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "text/html; charset=UTF-8");
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(content);
} catch (final IOException e) {
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
}

/**
* 获取配置文件
* @param propsName  配置文件名字
* @return
*/
public static String getPropertieValue(String propsName, String key) {
try {
InputStream inputStream;
final ClassLoader cl = UploadUtil.class.getClassLoader();
if (cl != null) {
inputStream = cl.getResourceAsStream(propsName);
} else {
inputStream = ClassLoader.getSystemResourceAsStream(propsName);
}
final Properties dbProps = new Proper
4000
ties();
dbProps.load(inputStream);
inputStream.close();
String p = dbProps.getProperty(key);
return dbProps.getProperty(key);
} catch (final Exception e) {
// TODO: handle exception
}
return "";
}

/**
*验证文件大小
* @param myfile
* @param stream
* @return
*/
public static String validateImg(MultipartFile myfile, InputStream stream) {
try {
final long size = myfile.getSize();
if (size > (1024 * 1023 * 10)) {
return UploadUtil.makeJsonResponse(false, "error1");
}

} catch (final Exception e) {
e.printStackTrace();
}
return "success";
}

/**
* 验证文件是否已经存在
* @param file
* @return
*/
public static String validateExistOrNo(File file){
if(file.exists()){
return UploadUtil.makeJsonResponse(false, "error3");
}
return "success";
}

/**
*判断字符串
* @param s
* @return
*/
public static boolean isNull(String s) {
if ((s == null) || s.equals("")) {
return true;
} else {
return false;
}
}
}


StringUtil的checkDir方法:

/**
* 检查文件夹是否存在, 不存在则创建
*
* @param path
*/
public static void checkDir(String path) {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
}


param.properties的上传路径配置:

uploadPlanpic.path=D\://PlanpicFiles




至此完成ajaxfileupload.js的异步上传
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息