首页 > 技术文章 > jquery ajax上传文件

jiduoduo 2016-12-22 12:25 原文

1、html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="jquery-2.1.0.js" type="text/javascript"></script>
</head>
<body>
<form id="form" enctype="multipart/form-data"> 
<div class="searchBar"> 
<table class="searchContent"> 
<tbody style="text-align:right;">
<tr > 
<td> 
<input name="img" type="file" value="请选择文件" id="img"></input> 
<input name="uid" type="text" value="1" id="uid"></input> 
<input name="message" type="text" value="10012" id="mesasge"></input>
</td> 
<td> 
<input type="button" value="上传" onclick="up();"></input> 
</td>
</tr> 
</tbody> 
</table> 
</div> 
</form> 
<script type="text/javascript">
function up(){
var formData = new FormData($("#form")[0]);
$.ajax({
type: "POST", 
url: "http://192.168.1.110:8080/aaUp.json",
data:formData, 
//必填 
processData: false, 
//必填 
contentType: false, 
dataType: "json", 
success: function(data){ 
alert(JSON.stringify(data));
},
error: function (data, status, e){//服务器响应失败处理函数
alert(JSON.stringify(data));
}
}); 
}
</script>
</body>
</html>

 

 

2、服务端代码:

以下提示,跨域问题:

Origin 'http://localhost:8080' is therefore not allowed access.
XHR failed loading: POST "http://192.168.1.110:8080/aaUp.json".
XMLHttpRequest cannot load http://192.168.1.110:8080/aaUp.json. No 'Access-Control-Allow-Origin' header is present on the requested resource

public String upload() throws Exception {
        String ct = ServletActionContext.getRequest().getHeader("Content-Type");
        ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin", "*");//解决跨域的问题
        String result = "unknow";
        String uid = getParameter("uid");
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        if (!filterType()) {
            SvrPrint.print("文件类型不正确");
            ServletActionContext.getRequest().setAttribute("typeError",
                    "您要上传的文件类型不正确");
            result = "error:" + getImgContentType()
                    + " type not upload file type";
            msg = "{\"filename\":\"\",\"msg\":\""+result+"\"}";
    
        } else {
            FileOutputStream fos = null;
            FileInputStream fis = null;
            try {
                // 保存文件那一个路径
                String filename = getImgFileName();
                fos = new FileOutputStream(getSavePath() + "\\" + uid + "_"
                        + filename);
                fis = new FileInputStream(getImg());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                msg =  "{\"filename\":\"390239023923.png\","msg":\"success\"}";
               //mResult是 一个对象,记录了一些返回信息,将手工修改
            } catch (Exception e) {
                result = "failed";
                msg = {\"filename\":\"\","msg":\""+result+"\"}";
            } finally {
                fos.close();
                fis.close();
            }
        }
        out.print(msg);
        //out.close(); java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
//http://java-linkin.iteye.com/blog/1953928
return SUCCESS; }

 

推荐阅读