Implementation of Java upload and download function

Source: Internet
Author: User
Tags button type

Upload download is a very simple function, but every time you use the time to check, here to tidy up

Front desk:

<form action= "xxoo.do" enctype= "Multipart/form-data" method= "POST" ><input type= "file" name= "file"/> < Button type= "Submit" class= "BTN btn-primary" > Submit </form>

Main Note:

Enctype= "Multipart/form-data" method= "POST"

Background:

Various frameworks have their own upload and download function, the implementation is very similar, after all, upload is to copy files, need an output stream. Through the firebug to see the upload, there will be two parameters to the background, one is the file stream, the variable name is consistent with the name in input, and one is the filename, the default is filename.

If you use Struts2. The filename is the variable name of the file stream +filename. As above is filefilename.

Backstage Direct: Fileutils.copyfile (Shopdatas, tempfile); there is no upload function using frames


If you download it, you're actually sending a inputstream to read the data out. Lazy to use the framework function, you can directly use the response response


Public void download (string newfilename) {Inputstream is = null;outputstream  os = null; Httpservletresponse response = servletactioncontext.getresponse (); try{String contentType= " Application/octet-stream ";   response.setcontenttype (ContentType);   response.setheader (" Content-disposition "," attachment;filename=\ "" +newfilename+ "\" "); Is=new bufferedinputstream (new  FileInputStream (NewFileName));    bytearrayoutputstream baos=new bytearrayoutputstream ();   os=new bufferedoutputstream (Response.getoutputstream ());     byte[]  buffer=new byte[4*1024];   int read=0;    while ((read= Is.read (buffer))!=-1) {      baos.write (buffer,0,read);  }   Os.write (Baos.tobytearray ());   }catch (exception e) {e.printstacktrace ();} Finally{closestream (os, is);}} 


Implementation of Java upload and download function

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.