jQuery版ajax实现文件上传

页面jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
	
	
	
  
  
  
    
用户名:
密码:
头像:

服务器端代码:

package com.min.action;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
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;
@WebServlet("/UploadAction")
@MultipartConfig
public class UploadAction extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			System.out.println("用户名:"+username+" 密码"+password);
			//获取上传的文件
			Part part=request.getPart("file");
			System.out.println("上传文件名:"+part.getSubmittedFileName());
			//上传文件夹在服务器的绝对路径
			String path=request.getServletContext().getRealPath("/upload");
			//将上传的问价写入服务器文件夹中
			part.write(path+"/"+UUID.randomUUID().toString()+part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf(".")));
			System.out.println("文件上传成功");
			response.getWriter().write("ok");
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().write("上传失败"+e.getMessage());
		}
		
	}

}

 

你可能感兴趣的:(前端)