jsp通过ajax上传文件,基于jquery

#前言

推荐讲解:使用ajax提交form表单,包括ajax文件上传

推荐讲解:HTML5+Ajax上传文件

建议:看这篇之前,请先了解直接form表单提交servlet方式上传文件  jsp上传文件到服务器,因为我下面servlet用的文件上传方式在里面有讲解,所以此篇不赘述。

#案例

前端jsp代码:

                <div style="width: 60%;text-align: center;margin: 2% auto;">
                    <input id="myphoto" type="file" name="pic">
                    <button type="button" onclick="uploadFiles('myphoto','photo')">提交</button>
                </div>

js代码实现uploadFiles函数,函数内执行ajax

/*** 上传文件 *****/
function uploadFiles(inputid,type) {
    var formData=new FormData();
    formData.append("file",$('#'+inputid).prop('files')[0]);
    formData.append('type',type);
    $.ajax({
        type:'POST',
        url:'/ServletUpload',
        data:formData,
        contentType: false,// 注意:让jQuery不要处理数据
        processData: false,// 注意:让jQuery不要设置contentType
        success:function (msg) {
            console.log("上传成功");
            window.location.reload();
        },
        error:function (mag) {
            console.log("上传失败,请重试");
            alert("上传失败,请重试");
            // window.location.reload();
        }
    });

}

最后是servlet代码:

package Servlet;

import Beans.User;
import Mysql.SQL;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet(name = "ServletUpload",urlPatterns = {"/ServletUpload"})
public class ServletUpload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        uploadFiles(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return;
    }

    private void uploadFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        PrintWriter out=response.getWriter();

        String ret="No";
        try {
            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);

            //获取普通参数
            Map<String ,String> field=new HashMap<>();
            for (FileItem item : formItems){
                if(item.isFormField()){
                    field.put(item.getFieldName(),item.getString());
                }
            }
            String type=field.get("type");//我自己规定的类型,区分文件是干嘛的

            int succ=0;
            // 迭代表单数据
            for (FileItem item : formItems) {
                // 处理不在表单中的字段,即文件
                if (!item.isFormField()) {
                    String fileName = item.getName(); //获取上传的文件名
                    String fileType=fileName.substring(fileName.lastIndexOf(".")+1);
                    //定义上传文件的存放路径
                    String path = request.getServletContext().getRealPath("/upload/"+type);
                    path=path.replace("\\","/");//一定要加上,不然路径在插入数据库时会出错
                    //定义上传文件的完整路径
                    String fileSaveName= new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
                    fileSaveName+="."+fileType;
                    String filePath = String.format("%s/%s",path,fileSaveName);
                    File storeFile = new File(filePath);
                    //如果父目录不存在,就创建他
                    if(!storeFile.getParentFile().exists()){
                        storeFile.getParentFile().mkdirs();
                    }
                    // 在控制台输出文件的上传路径
                    System.out.println(filePath);
                    // 保存文件到硬盘
                    item.write(storeFile);




                    //以下是将路径信息插入数据库,不必关注
                    /******............******/
                    succ++; //多上传了一个文件

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        if(succ>0){
            ret="Yes";
        }
        out.print(ret);
        out.flush();
        out.close();
    }

}

如有错误,请帮我指正,谢谢

 

相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:马嘣嘣 返回首页