File upload--based on spring MVC framework +smartupload

Source: Internet
Author: User

This article is an introduction to file upload, due to the implementation of spring MVC and directly in the servlet write a little different, so specifically wrote this article, about the different points, you can first read the previous article. OK, here's the code directly.

Jab package is Jspsmartupload.jar, if there is a similar jar package such as: commons-fileupload-1.2.2, leave one can, otherwise conflict error

The first is a simple page (JSP), ugly, but can use:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "    pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


Then the controller code, as for why this is written, you can refer to the previous article:

Package Module.system.controller;import Java.io.ioexception;import Javax.servlet.servletconfig;import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Module.system.common.fileload;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Org.springframework.web.bind.annotation.responsebody;import Org.springframework.web.context.ServletConfigAware; Import org.springframework.web.context.servletcontextaware;/** * File upload download. * */@Controller @requestmapping ("/fileload") public class Fileloadcontroller implements Servletconfigaware, Servletcontextaware{private ServletContext ServletContext, @Overridepublic void Setservletcontext (ServletContext    arg0) {this.servletcontext = arg0;} Private ServletConfig ServletConfig; @Overridepublic void Setservletconfig (ServletConfig arg0) {this.servletconfig = arg0;} @RequestMapping (value = "/upload.do", method = Requestmethod.post) @ResponseBody//This note indicates that the return value skips the View Processing section and writes directly to the HTTP response Body public String Upload (httpservletrequest request,httpservletresponse response) {Fileload fileload = new Fileload (); try {fileload.upload (request, Response,servletconfig),} catch (Servletexception e) {e.printstacktrace ();} catch ( IOException e) {e.printstacktrace ();} Return "";}}
Next is the Fileload class:

Package Module.system.common;import Java.io.ioexception;import Java.text.dateformat;import Java.text.simpledateformat;import Java.util.date;import Java.util.random;import Javax.servlet.ServletConfig; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.jspsmart.upload.smartfile;import com.jspsmart.upload.smartupload;/** * File upload download. * @author Nagsh. * */public class fileload{/** * File upload. * @param request * @param response * @return * @throws servletexception * @throws IO Exception */public String Upload (httpservletrequest request, HttpServletResponse response,servletconfig config) throws Servletexception, IOException {request.setcharacterencoding ("utf-8");//Create a new Smartupload object Smartupload mySmartUpload =new smartupload (); String fileId = ""; try{//upload initialization mysmartupload.initialize (config, request, response);// Set the maximum length of each uploaded file Mysmartupload.setmaxfilesize (1*512*1024);//Set the length of the total upload data mysmArtupload.settotalmaxfilesize (1*1024*1024);//Set the type of files allowed to upload, only allow uploading of java,doc,txt files Mysmartupload.setallowedfileslist ("Java,doc,txt");//Set the type of file that is forbidden to upload, prohibit uploading with Exe,bat file Mysmartupload.setdeniedfileslist ("Exe,bat");// Upload file Mysmartupload.upload ();//process each upload file for (int i=0;i<mysmartupload.getfiles (). GetCount (); i++) {Smartfile file= Mysmartupload.getfiles (). GetFile (i);//Determine if the user has selected the file if (!file.ismissing ()) {//save to the directory at the root of the Web application as the root directory of the file//( To declare: In MyEclipse, the directory is located under engineering. Metadata/.me_tcat/webapps/the Project Catalog/upload/)//Generate a unique file index (date + two random number) String FileName =                    File.getfilename ();                    String data[] = filename.split ("\ \");                    System.out.println (data.length);   String fileType = data[1]; File type System.out.println (fileType);D ate now = new Date ();D ateformat YMD = new SimpleDateFormat ("Yyyymm DD ");//year-month-day string ymd = Ymd.format (now);//Current year-month-day random random = new random (), int r1 = Random.nextint (99999); int r2 = Ran Dom.nextint (99999); fileId = ymd+r1+ "" +R2; System.out.println(fileId); File.saveas ("/upload/" +fileid+ ".") +filetype,mysmartupload.save_virtual);}}} catch (Exception e) {//exception handling//Print custom exception information}return fileId;} public static void Main (string[] args) {}}
Write a button when the test, click on the page to pop up on the line.

File upload name is randomly generated, this block can be changed according to the actual situation, the code to write clear.

Also to emphasize is that I wrote this example file is uploaded to the tomcat/webapps/project/upload, so you need to create a folder under Tomcat first.




File upload--based on spring MVC framework +smartupload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.