Java upload attachments, bulk download attachments (i)

Source: Internet
Author: User

Upload attachment code: with Commons-fileupload-1.2.jar

Package com.str;

Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import Java.util.Iterator;
Import java.util.List;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.commons.fileupload.FileItem;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Uploadservlet extends HttpServlet {

@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
Doget (req, resp);
}


@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {

HttpServletRequest request = (httpservletrequest) req;
HttpServletResponse response = (httpservletresponse) resp;

/* Response.setcontenttype ("text/html;charset=gb2312");
Response.setcharacterencoding ("Utf-8"); */

OutputStream outputstream = null;
InputStream inputstream = null;

Diskfileitemfactory factory = new Diskfileitemfactory ();
Servletfileupload fileUpload = new Servletfileupload (factory);

try {
List items = fileupload.parserequest (request);
for (Iterator Iterator = Items.iterator (); Iterator.hasnext ();) {
Fileitem name = (Fileitem) iterator.next ();
if (!name.isformfield ()) {
String fieldName = Name.getfieldname (); This is the name value.
String fileName = Name.getname (); This is the full path.
String lastfilename = "";

This sentence gets the original name of the source file, without making any modifications
String Oldnamepath = filename.substring (filename.lastindexof ("\ \") +1);

if (Filename.endswith (". docx") | | filename.endswith (". xls")) {

Lastfilename = Request.getrealpath ("/") + "\\upload\\" + oldnamepath;
OutputStream = new FileOutputStream (new File (Lastfilename));

InputStream = Name.getinputstream ();
Byte[] bs = new byte[1024];
int length = 0;
while (null! = InputStream && (length = Inputstream.read (BS))!=-1) {
Outputstream.write (BS);
}
}
Outputstream.flush ();
}
Save the Lastfilename to the database (this is not the way to write the LZ)}
}
} catch (Exception e) {
E.printstacktrace ();
}

}
}

Single download file, bulk download file code: With the help of Ant.jar package Zipoutputstream, ZipEntry

Package com.str;

Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.tools.zip.ZipEntry;
Import Org.apache.tools.zip.ZipOutputStream;

Public class loadservlet  extends HttpServlet {
 
  @Override
 /*protected void Doget ( HttpServletRequest req, HttpServletResponse resp)
   throws servletexception, IOException {
  
  string path = Getservletcontext (). Getrealpath ("/") + "\\upload";
  outputstream o = Resp.getoutputstream ();
  byte b[] = new byte[1024];
  
  //files in this place can be found dynamically from the database, and I'm dead here. To simply show the
  file fileload = new File (path, " Resolve type configuration. xls ");
  
  string filename = new String ("Resolve type configuration. xls". GetBytes ("GBK"), "iso8859-1");

SYSTEM.OUT.PRINTLN (filename);

I remember when I exported the data in Excel said that filename must not write Chinese, in fact, after the following:
string filename = new String ("Resolve type configuration. xls". GetBytes ("GBK"), "iso8859-1");
After conversion, whether the file is Chinese, English, will not appear garbled situation, I have verified

Resp.setheader ("Content-disposition", "attachment;filename=" + filename);

Long filelength = Fileload.length ();
String length = string.valueof (filelength);
Resp.setheader ("Content_length", Length);
FileInputStream in = new FileInputStream (fileload);
int n = 0;
while ((n = in.read (b))! =-1) {
O.write (b, 0, N);
}
}*/

The above is a single download attachment, here is the bulk compression download accessories
protected void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {

String zipfilename = "Test.zip";

These files are all there, I'm dead, I can send names from the page.
String[] Filepatharray = {"1.jpg", "2.jpg", "3.xls", "Test. docx"};
String path = Getservletcontext (). Getrealpath ("/") + "\\image";

Resp.setcontenttype ("Application/x-msdownload"); Notifies the client of the MIME type of the file:
Resp.setheader ("Content-disposition", "attachment;filename=" + zipfilename);

Zipoutputstream Zos = new Zipoutputstream (Resp.getoutputstream ());

for (String Filepath:filepatharray) {
File File = new file (path + file.separator + FilePath);
Dozip (file, Zos);
}
Zos.close ();
}

File compression issues when processing bulk downloads
private void Dozip (file file, Zipoutputstream Zos) throws IOException {
if (file.exists ()) {
if (File.isfile ()) {
If it is a file, write to the zip stream
String fileName = File.getname ();

ZipEntry Zet = new ZipEntry (File.getname ());
Zos.putnextentry (Zet);
FileInputStream fis = new FileInputStream (file);
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read (buffer))! =-1) {
Zos.write (buffer, 0, R);
}
Zos.setencoding ("GBK"); This place is important.
Zos.flush ();
Fis.close ();
}else {
System.out.println ("Not a file, that will not be downloaded, because the front desk will do the processing, here is not step by step to verify!");
}
}
}

}


Java upload attachments, bulk download attachments (i)

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.