SpringMVC combines with ajaxfileupload.js to achieve no refreshing upload of files

  • 2020-05-10 18:18:57
  • OfStack

The example of this article is to share the ajaxfileupload.js implementation file without the refresh upload of the specific code, for your reference, the specific content is as follows

Just look at the code. The comments are in there

The first is web xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
 <description> configuration SpringMVC Front end controller </description>
 <servlet-name>upload</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>upload</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
 
 <filter>
 <description> Solve the problem of garbled code in the process of parameter passing </description>
 <filter-name>CharacterEncodingUTF8</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
 <param-name>encoding</param-name>
 <param-value>UTF-8</param-value>
 </init-param>
 </filter>
 <filter-mapping>
 <filter-name>CharacterEncodingUTF8</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

The following is located at //src// applicationContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 <!--  Start the Spring Component automatic scanning mechanism (Spring It will automatically scan base-package Class in the specified package and subpackage ) -->
 <!--  See my article here http://blog.csdn.net/jadyer/article/details/6038604 -->
 <context:component-scan base-package="com.jadyer"/>
 
 <!--  Start the SpringMVC Annotation function , It's automatically registered HandlerMapping , HandlerAdapter , ExceptionResolver Related examples of  -->
 <mvc:annotation-driven/>
 
 <!--  Due to the web.xml Set in the SpringMVC Intercept all requests , So you can't read static resource files when you read them  -->
 <!--  This configuration allows you to specify all requests or references "/js/**" The resources of , from "/js/" Look for  -->
 <mvc:resources mapping="/js/**" location="/js/"/>
 <mvc:resources mapping="/upload/**" location="/upload/"/>
 
 <!-- SpringMVC When uploading a file , Need to configure MultipartResolver The processor  -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
 <!--  Specifies that the total size of the uploaded file must not exceed 800KB...... Pay attention to maxUploadSize Property restrictions are not specific to a single file , It's the sum of all the files  -->
 <property name="maxUploadSize" value="800000"/>
 </bean>
 
 <!-- SpringMVC When the upload file limit is exceeded , Will be thrown org.springframework.web.multipart.MaxUploadSizeExceededException -->
 <!--  The exception is SpringMVC Thrown up while checking the uploaded file information , And it's not in yet Controller In the method  -->
 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
 <property name="exceptionMappings">
 <props>
 <!--  encounter MaxUploadSizeExceededException When abnormal , Automatic jump to /WEB-INF/jsp/error_fileupload.jsp page  -->
 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
 </props>
 </property>
 </bean>
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/jsp/"/>
 <property name="suffix" value=".jsp"/>
 </bean>
</beans>

The following is the prompt page for uploading the content of the file when it is too large // WEB-INF //jsp// error_fileupload.jsp
< %@ page language="java" pageEncoding="UTF-8"% >
< h1 > File is too large, please re - select < /h1 >

Below is the upload page index.jsp for selecting files


<%@ page language="java" pageEncoding="UTF-8"%>
<!--  I can't abbreviate this to <script type="text/javascript" src=".."/> -->
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script>

<script type="text/javascript">
function ajaxFileUpload(){
 // Displays when the file is uploaded 1 A picture , File upload is completed to hide the image 
 //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});
 // The function that performs the upload of a file 
 $.ajaxFileUpload({
 // The server-side address where the file upload operation is processed ( You can pass parameters , Already tested and available )
 url:'${pageContext.request.contextPath}/test/fileUpload?uname= XuanYu ',
 secureuri:false,      // Whether to enable secure commit , The default is false 
 fileElementId:'myBlogImage',   // File selection box id attribute 
 dataType:'text',      // The format returned by the server , Can be json or xml Etc. 
 success:function(data, status){  // The server responds successfully to the handler function 
 data = data.replace("<PRE>", ''); //ajaxFileUpload It will respond back to the server text The content and <pre>text</pre> Before the suffix 
 data = data.replace("</PRE>", '');
 data = data.replace("<pre>", '');
 data = data.replace("</pre>", ''); // In this example, after the upload file is completed , The server will return to the front desk [0`filepath]
 if(data.substring(0, 1) == 0){  //0 Means the upload is successful ( Followed by the uploaded file path ),1 Said failure ( Heel failure description )
 $("img[id='uploadImage']").attr("src", data.substring(2));
 $('#result').html(" Picture uploaded successfully <br/>");
 }else{
 $('#result').html(' Picture upload failed, please try again!! ');
 }
 },
 error:function(data, status, e){ // The handler function when the server response fails 
 $('#result').html(' Picture upload failed, please try again!! ');
 }
 });
}
</script>

<div id="result"></div>
<img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">

<input type="file" id="myBlogImage" name="myfiles"/>
<input type="button" value=" To upload pictures " onclick="ajaxFileUpload()"/>

<!-- 
AjaxFileUpload Introduction to the 
 website :http://phpletter.com/Our-Projects/AjaxFileUpload/
 Introduction to the :jQuery The plug-in AjaxFileUpload Can achieve no refresh upload file , And it's easy to use , It is used by a large number of people , Highly recommended 
 Pay attention to : The introduction of js The order of ( It depends on the jQuery) There is no form in the and page ( It's just triggered when the button is clicked ajaxFileUpload() methods )
 Common errors and solutions are as follows 
1)SyntaxError: missing ; before statement
 -- check URL Whether the path is accessible 
2)SyntaxError: syntax error
 -- Check for handling the commit operation JSP Whether there is a syntax error in the file 
3)SyntaxError: invalid property id
 -- Check the properties ID If there is a 
4)SyntaxError: missing } in XML expression
 -- Check whether the file's domain name is 1 To or not to exist 
5) Other custom errors 
 -- Usable variable $error The direct printing method checks that the parameters are correct , This is much more convenient than the invalid error prompts above 
 -->

Finally, FileUploadController.java, which handles file uploads


package com.jadyer.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * SpringMVC File upload in 
 * 1) Due to the SpringMVC Using the commons-fileupload implementation , So the first step is to introduce its components into the project 
 * 2) in SpringMVC Configuration in the configuration file MultipartResolver The processor ( You can add property restrictions to uploaded files here )
 * 3) in Controller Is added to the MultipartFile parameter ( This parameter is used in the receive form file Content of a component )
 * 4) Writing the foreground form ( Pay attention to enctype="multipart/form-data" As well as <input type="file" name="****"/>)
 * PS: Because it's used here ajaxfileupload.js Realize no refresh upload , So the form is not used in this example 
 * ---------------------------------------------------------------------------------------------
 *  The following is used here jar
 * commons-io-2.4.jar
 * commons-fileupload-1.3.jar
 * commons-logging-1.1.2.jar
 * spring-aop-3.2.4.RELEASE.jar
 * spring-beans-3.2.4.RELEASE.jar
 * spring-context-3.2.4.RELEASE.jar
 * spring-core-3.2.4.RELEASE.jar
 * spring-expression-3.2.4.RELEASE.jar
 * spring-jdbc-3.2.4.RELEASE.jar
 * spring-oxm-3.2.4.RELEASE.jar
 * spring-tx-3.2.4.RELEASE.jar
 * spring-web-3.2.4.RELEASE.jar
 * spring-webmvc-3.2.4.RELEASE.jar
 * ---------------------------------------------------------------------------------------------
 * @create Sep 14, 2013 5:06:09 PM
 * @author  XuanYu <http://blog.csdn.net/jadyer>
 */
@Controller
@RequestMapping("/test")
public class FileUploadController {
 /**
 *  I'm going to use theta here MultipartFile[] myfiles parameter , So you need to use the front desk <input type="file" name="myfiles"/>
 *  After uploading the file, return it to the reception desk [0`filepath],0 Means the upload is successful ( Followed by the uploaded file path ),1 Said failure ( Heel failure description )
 */
 @RequestMapping(value="/fileUpload")
 public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{
 // You can upload files and receive other parameters at the same time 
 System.out.println(" They receive [" + uname + "] File upload request ");
 // If you use theta Tomcat Server, the file will be uploaded \\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\ folder 
 // The file upload operation is implemented here commons.io.FileUtils class , It will automatically determine /upload If there is a , None will be created automatically 
 String realPath = request.getSession().getServletContext().getRealPath("/upload");
 // Sets the data format for the response to the foreground content 
 response.setContentType("text/plain; charset=UTF-8");
 // Sets the response to the foreground content PrintWriter object 
 PrintWriter out = response.getWriter();
 // The original name of the uploaded file ( The name of the file before uploading )
 String originalFilename = null;
 // If you just upload 1 A file , Only need to MultipartFile Type receive file , And you don't have to specify it explicitly @RequestParam annotations 
 // If you want to upload multiple files , So we're going to use it here MultipartFile[] Type to receive the file , And to specify @RequestParam annotations 
 // When uploading multiple files , All in the foreground form <input type="file"/> the name Everything ought to be myfiles, Otherwise in the parameter myfiles Unable to access all uploaded files 
 for(MultipartFile myfile : myfiles){
 if(myfile.isEmpty()){
 out.print("1` Please select the file and upload it ");
 out.flush();
 return null;
 }else{
 originalFilename = myfile.getOriginalFilename();
 System.out.println(" File formerly known as : " + originalFilename);
 System.out.println(" The file name : " + myfile.getName());
 System.out.println(" The length of the file : " + myfile.getSize());
 System.out.println(" The file type : " + myfile.getContentType());
 System.out.println("========================================");
 try {
  // I don't have to deal with that IO Flow closure problem , because FileUtils.copyInputStreamToFile() It will be used automatically inside the method IO Flow switch off 
  // You can also use it here Spring To provide the MultipartFile.transferTo(File dest) Method to upload a file 
  FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));
 } catch (IOException e) {
  System.out.println(" file [" + originalFilename + "] Upload failed , The stack trace is as follows ");
  e.printStackTrace();
  out.print("1` File upload failed, please try again!! ");
  out.flush();
  return null;
 }
 }
 }
 // At this point in Windows The next output is [D:\Develop\apache-tomcat-6.0.36\webapps\AjaxFileUpload\\upload\ Angry birds .jpg]
 //System.out.println(realPath + "\\" + originalFilename);
 // At this point in Windows The next output is [/AjaxFileUpload/upload/ Angry birds .jpg]
 //System.out.println(request.getContextPath() + "/upload/" + originalFilename);
 // Return is not recommended [realPath + "\\" + originalFilename] The value of the 
 // Because in the Windows Under the <img src="file:///D:/aa.jpg"> Can it be firefox According to , while <img src="D:/aa.jpg">firefox Is not recognized 
 out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);
 out.flush();
 return null;
 }
}

For more exciting content, please refer to the special topics "ajax upload technology summary", "javascript file upload operation summary" and "jQuery upload operation summary" for learning.


Related articles: