File upload--+smartupload__ framework based on Spring MVC framework

Source: Internet
Author: User
Tags date now dateformat

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

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

First is a simple page (JSP), more ugly, but can be used:

<%@ 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" >
Effect Chart:


Then the controller code, as for why to write, 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;
	@Override public void Setservletcontext (ServletContext arg0) {this.servletcontext = arg0; } private ServletConfig servletconfig;
	@Override public 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 RESPO NSE body in public String upload (httpservletrequest request,httpservletresponse response) {Fileload fileload = new F
		Ileload ();
		try {fileload.upload (request, response,servletconfig);
		catch (Servletexception e) {e.printstacktrace ();
		catch (IOException e) {e.printstacktrace ();
	Return "";
 }

	
}
followed by 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 ioexception/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 file allowed to upload, only allow upload Java,doc,txt file mysmartupload.setallowedfileslist ("Java,doc,txt");
			Set the type of file prohibited 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 (). g
				Etfile (i); Determine if the user has selected the file if (!file.ismissing ()) {//saved to the directory with the root of the Web application as the root of the file//(declare: In MyEclipse, the directory is under engineering. Metadata/.me_
                    tcat/webapps/the Engineering directory/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);
					Date now = new Date (); DateFormat YMD = new SimpleDateFormat ("YyyyMMdd//year-month-day String ymd = Ymd.format (now);/Current year-month-day Random Random = new Random ();
					int r1 = Random.nextint (99999);
					int r2 = Random.nextint (99999);
					Fileid = ymd+r1+ "" +R2;
					System.out.println (Fileid); File.saveas ("/upload/" +fileid+ ")."
				+filetype,mysmartupload.save_virtual);
	}}catch (Exception e) {//exception handling//Printing custom exception information} return Fileid;
 public static void Main (string[] args) {}}
When testing, write a button, click on the top of the page to pop up on the line.

File upload after the name is randomly generated, this piece can be changed according to the actual situation, the code written understand.

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




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.