File upload and file compression download

Source: Internet
Author: User
Tags arrays bind file upload flush rar zip

Import Java.io.BufferedInputStream;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.ArrayList;
Import Java.util.Arrays;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;


Import javax.annotation.PostConstruct;
Import Javax.servlet.ServletContext;
Import Javax.servlet.ServletOutputStream;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;


Import Org.apache.commons.lang3.StringUtils;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
Import Org.springframework.web.context.ContextLoader;
Import Org.springframework.web.context.WebApplicationContext;
Import Org.springframework.web.multipart.MultipartFile;



@Controller
@RequestMapping ("/file")
public class Filecontroller extends Baseaction {


Private final static Logger log = Loggerfactory.getlogger (Filecontroller.class);


private static long MAXSIZE = 500000;

private static int cache_byte_length=1024;
private static String comma= ",";


private static String Allowfileext = ". Png,.jpg,.jpeg,.xls,.pdf,.doc,.rar,.zip,.txt,.mp3,.mp4,.avi";

private static String Savedfileext = ". png";


private static String Imgfileext = ". Png,.jpg,.jpeg";

private static String Picstorepath = null;
@Autowired
Private Iextconfigparamservice Extconfigparamservice;
@PostConstruct
public void init () {
if (resourceutil.getallowfileext () = null) {
Allowfileext = Resourceutil.getallowfileext ();
}
Picstorepath=extconfigparamservice.fetchvalue (Constant.pic_storepath);

if (Stringutils.isnotempty (Picstorepath)) {
picstorepath=picstorepath+ "/";
}
}

public static void Deletezip (String realpath) {
Get file objects by path
File File = new file (Realpath);
Determine if a file exists
if (file.exists ()) {
File deletion
File.delete ();
System.out.println ("Delete succeeded" +realpath);
}
}

public static void DeleteFile (File f) {
For (File fi:f.listfiles ()) {
if (Fi.isdirectory ()) {
DeleteFile (FI);
}
else{
Fi.delete ();
}
}
F.delete ();
}


@RequestMapping ("/download")
public void Download (HttpServletRequest request, httpservletresponse response) {
try {
System.out.println ("Lai");
String Cusid = Request.getparameter ("cus_id");
String Applyid = Request.getparameter ("apply_id");
Folder path
String src= GetPath ("/web-inf/upload/pls/" +cusid+ "/" +applyid);
The copy will compress the file path
String Path = GetPath ("/web-inf/upload/pls/" +cusid+ "/" +applyid) + "1";
Copy a modified name compress download
Copydirectory.copy (src, path);
File file= new file (path);
Updatefilename.renamefile (file);
New Compactalgorithm (New File (path+)/. /", applyid+". zip ")). Zipfiles (file);

String filename = applyid+ ". zip";
Compressed file full
String Realpath = path+ "/". /"+applyid+". zip ";
InputStream fis = new Bufferedinputstream (new FileInputStream (Realpath));
Response.setheader ("Content-disposition", "attachment;filename=" +filename);
byte [] bts = new byte [cache_byte_length];
int len = 0;
OutputStream outputstream = new Bufferedoutputstream (Response.getoutputstream ());
while ((Len=fis.read (BTS, 0, Cache_byte_length))!=-1) {
Outputstream.write (BTS, 0, Len);
}
Outputstream.flush ();
Fis.close ();
Outputstream.close ();
DeleteFile (file);
Deletezip (Realpath);
} catch (Exception ex) {
Ex.printstacktrace ();
}

}


@RequestMapping (value = "/upload", method = Requestmethod.post)
public void Upload (@RequestParam (value = "file") Multipartfile file,
@RequestParam (value = "files") multipartfile[] files, httpservletrequest request,
HttpServletResponse response) throws Exception {
If you are uploading only one file, you only need to receive the file Multipartfile type, and you do not need to explicitly specify @requestparam annotations
If you want to upload multiple files, you will need to use the multipartfile[] type to receive the file, and also specify the @requestparam annotation
And when uploading multiple files, all <input in the foreground form
type= "file"/> name should be myfiles, otherwise the myfiles in the parameter can not get all the uploaded files
enctype = "Multipart/form-data"
Map<string, object> context = new hashmap<> (5);
list<string> fileNames = new arraylist<> ();

for (int i=0;i<files.length;i++) {
Filenames.add (UploadFile (i,files[i], request, response));
}


Filenames.add (UploadFile (0,file, request, response));
Context.put (SUCCESS, true);
Context.put ("Data", fileNames);
Context.put ("StatusCode", "200");
Context.put ("filename", fileNames);


Htmlutil.writerjson (response, context);
}


/**
* Get file path
* Note: Priority is obtained from the configuration file
*/
private string GetPath (string path) {

String FilePath = Resourceutil.getfilepath ();
if (Stringutils.isnotempty (FilePath)) {
return Resourceutil.getfilepath () + path;
}


Webapplicationcontext Webapplicationcontext = Contextloader.getcurrentwebapplicationcontext ();
if (webapplicationcontext! = null) {
ServletContext ServletContext = Webapplicationcontext.getservletcontext ();
return Servletcontext.getrealpath (path);
}

return path;
}

@RequestMapping (value = "/imageurl", method = Requestmethod.get)
public void ImageUrl (HttpServletRequest request, httpservletresponse response) throws ioexception{
String Path = request.getparameter ("path");
String Supportall = Request.getparameter ("Supportall");
String Directopen = Request.getparameter ("Directopen");
String template = Request.getparameter ("template");
String Loadpath=null;
if (template==null) {
Loadpath= "/web-inf/upload/" +picstorepath;
}else{
Loadpath= "/web-inf/filetemplate/";
}
IMAGEURL (Path,supportall,directopen,loadpath,response);
}

@RequestMapping (value = "/imagetemplateurl", method = Requestmethod.get)
public void Imagetemplateurl (HttpServletRequest request, httpservletresponse response) throws ioexception{
String Path = request.getparameter ("path");
String Supportall = Request.getparameter ("Supportall");
String Directopen = Request.getparameter ("Directopen");
IMAGEURL (Path,supportall,directopen, "/web-inf/filetemplate/", response);
}

private void ImageUrl (String path,string supportall,string directopen,string filepath,httpservletresponse response) Throws ioexception{
Boolean isimage=false;
String Suffix=savedfileext;
String Realpath = GetPath (FilePath);
Log.debug ("Realpath-----------------:" +realpath);

String Filename=null;
String Filepath=null;
int Separatorindex=path.lastindexof ("/");
if (separatorindex!=-1) {
Filename=path.substring (separatorindex+1);
Filepath=path.substring (0, Separatorindex);
}else{
Filename=path;
}

if (!path.endswith (suffix)) {

String Filepackage=realpath;
if (filepath!=null) {
Filepackage=realpath+file.separator+filepath;
}

file[] fs = new File (filepackage). Listfiles ();

if (fs!=null) {
Long lastmodified=0;
for (File F:fs) {
if (F.getname (). StartsWith (filename)) {
if (F.lastmodified () ==lastmodified&&f.getname (). EndsWith (Savedfileext)) {
Suffix=savedfileext;
}else if (f.lastmodified () >lastmodified) {
Lastmodified=f.lastmodified ();
Suffix=stringutils.remove (F.getname (), filename);
}
}
}
Path=path+suffix;
}
}

if (imgfileext.indexof (suffix)!=-1) {
Isimage=true;
}

String contenttype= "Image/png";
File Picfile = new file (Realpath+file.separator+path);
Log.debug ("Picfile-----------------:" +picfile.getpath ());
if (!picfile.exists ()) {
Path = Stringutils.remove (Realpath,picstorepath.replace ("/", "")) + "/error.jpg";
Picfile = new File (path);
Suffix=savedfileext;
}else if (!isimage&&supportall==null) {
is not a picture, and is a thumbnail, use a dummy thumbnail
Path = Stringutils.remove (Realpath,picstorepath.replace ("/", "")) + "/notimg.jpg";
Picfile = new File (path);
Suffix=savedfileext;
}else{
Response.setheader ("Cache-control", "No-cache");
Response.setheader ("Cache-control", "No-store");
Response.setheader ("Pragma", "No-cache");
Response.setdateheader ("Expires", 0);

switch (suffix) {
Case ". png":
Contenttype= "Image/png";
Break
Case ". jpg":
Contenttype= "Image/jpg";
Break
Case ". JPEG":
Contenttype= "Image/jpeg";
Break
Case ". xls":
Contenttype= "Application/x-xls";
Break
Case ". pdf":
Contenttype= "Application/pdf";
Break
Case ". zip":
Contenttype= "Application/zip";
Break
Case ". rar":
Contenttype= "Application/octet-stream";
Break
Default
Contenttype= "Image/png";
Break
}
}

Response.setcontenttype (contenttype+ "; CHARSET=GBK");
if (directopen==null) {
Open directly, you do not need to add the following sentence
Response.setheader ("Content-disposition", "attachment; Filename= "+new String ((filename+suffix). GetBytes (" GBK ")," iso8859_1 ");
}
Servletoutputstream Outputstream=null;
FileInputStream Inputstream=null;
try {
OutputStream = Response.getoutputstream ();
InputStream = new FileInputStream (picfile);
byte[] buffer = new byte[1024];
int i =-1;
while ((i = inputstream.read (buffer))! =-1) {
Outputstream.write (buffer, 0, I);
}
} catch (IOException e) {
E.printstacktrace ();
} finally{
if (outputstream!=null) {
Outputstream.flush ();
Outputstream.close ();
OutputStream = null;
}
if (inputstream!=null) {
Inputstream.close ();
}
}
}

Private String uploadfile (int i,multipartfile e, httpservletrequest request, httpservletresponse response)
Throws Exception {
if (E.isempty ()) {
Log.debug ("File not uploaded");
} else {
Log.debug ("File length:" + e.getsize ());
Log.debug ("File type:" + e.getcontenttype ());
Log.debug ("File name:" + e.getname ());
Log.debug ("File formerly known as:" + e.getoriginalfilename ());


if (E.getsize () > MAXSIZE) {
Sendfailuremessage (response, E.getname () + "Upload file exceeds the limit size. ");
return null;
}


String fileext = "."
+ e.getoriginalfilename (). substring (E.getoriginalfilename (). LastIndexOf (".") + 1). toLowerCase ();
if (! Arrays.<string>aslist (Allowfileext.split (COMMA)). Contains (Fileext)) {
Sendfailuremessage (response, "The upload file extension is not allowed. \ n only allow "+ Allowfileext +" format. ");
return null;
}


String dir=request.getparameter ("dir");
String picname=request.getparameter ("Picname");
if (i!=0) {
Picname=picname+i;
}
String Realpath = GetPath ("/web-inf/upload/" +picstorepath+dir);
There is no need to deal with the problem of Io stream shutdown, because the Fileutils.copyinputstreamtofile () method will automatically shut down the IO stream used, I see it's source code to know

File Filedest = new file (Realpath);


If the destination folder does not exist
if (!filedest.isdirectory () | |!filedest.exists ()) {
if (!filedest.mkdirs ()) {
Log.debug ("Directory folder not saved, failed when creating destination folder!");
return null;
}
}
File Srcfile = new file (Realpath, picname+savedfileext);//e.getoriginalfilename () +fileext
E.getoriginalfilename () +fileext
File Srcfile = new file (Realpath, picname+fileext);
System.out.println (Srcfile.getabsolutepath ());
E.transferto (Srcfile);
return Srcfile.getname ();
}
return null;
}


}

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.