Cos implementation file upload--recommended

Source: Internet
Author: User
Tags cos

1. Guide Package

2. Core class: Multipartrequest

Multipartrequest is the packaging class for request

Parameter 1:request

Parameter 2: Save path

Parameter 3: Upload file size, default is 1M

Parameter 4: Encoding

Parameter 5: Rename filerenamepolicy, the default renaming format is to add a number after the name

Parameters can be used as needed

3, compared with apache-upload

1, can upload multiple files directly, without traversing

2, get text and other simple text without judgment

3, can be named by default

4. Demo

1String Path=getservletcontext (). Getrealpath ("File");2Filerenamepolicy rename=NewDefaultfilerenamepolicy ();//Renamed By default, followed by name: name. jpg, name 1.jpg, name 2.jpg3Multipartrequest req=NewMultipartrequest (Request, Path, 1024*1024*10, "Utf-8"), rename);4             5             //Get upload file information6Response.setcontenttype ("Text/html;charset=utf-8");7PrintWriter out=Response.getwriter ();8Out.write ("File name:" +req.getoriginalfilename ("file"));9Out.write ("<br/> new filename:" +req.getfilesystemname ("file"));TenOut.write ("<br/> file type: +req.getcontenttype")); OneOut.write ("<br/> Size:" +req.getfile ("file"). Length ()); AOut.write ("<br/> Description:" +req.getparameter ("desc")); -Out.write ("</img> "); -     

In the above code, if the upload is a Chinese named picture, it will not display properly, so we need to rename, implement the Filerenamepolicy interface

1 classMyrenameImplementsFilerenamepolicy2 {3      Publicfile Rename (file file) {4String filename=file.getname ();5String extname=filename.substring (Filename.lastindexof (".")));6String Uuid=uuid.randomuuid (). toString (). Replace ("-", "" ");7String newname=uuid+Extname;8file=NewFile (File.getparent (), newName);9         returnfile;Ten     } One      A}

Call Rename

Multipartrequest req=Newnew myrename ());

Cos implementation file upload--recommended

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.