使用Java Servlet和AJAX上传图像

时间:2013-09-08 12:36:57

标签: java javascript jquery ajax servlets

我正在尝试实现允许用户将图像上传到我的网站的功能。下面是我用来尝试POST文件的JavaScript文件以及从下拉列表到Servlet的选择:

function uploadImage(){

  var formData = new FormData();
  var file = document.getElementById("FileUpload").files[0];    
  var currPackage = $('#imageClassSelection option:selected').text();
  var currClass = $('#imageComponentSelection option:selected').text();
  formData.append("fileUpload", file);
  formData.append("currPackage", currPackage);
  formData.append("currClass",currClass);
  $.ajax({
    url: 'ImageFileUpload',  //server script to process data
    type: 'POST',
    data: formData,
    cache: false,
    contentType: false,
    processData: false
  }).done(function( data ) {
    //output to screen .append
  });
}

这也是我发布的Java Servlet:

@WebServlet("/ImageFileUpload")
@MultipartConfig
public class ImageFileUpload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageFileUpload() {
        super();
        // TODO Auto-generated constructor stub
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
     protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException {

         Properties properties = new Properties();
         properties.load(new FileInputStream("C:\\Users\\workspace\\XMLGenerator\\FTFXmlGenerator\\ftf.properties"));
         String imageDir = properties.getProperty("images");
         HttpSession session = request.getSession(true);
         String version = session.getAttribute("frameworkVersion").toString();
         System.out.println(request.getParameter("currPackage"));
         System.out.println(request.getParameter("currClass"));
     }

}

我尝试过以下方法:

http://www.technicaladvices.com/2011/12/10/ajax-file-upload-to-a-java-servlet-in-html5/

0 个答案:

没有答案