Struts implements file uploads and downloads.

Source: Internet
Author: User

First to implement the upload.

Write upload regardless of language, you should first notice the front-end form there is a detail.

<name= "Form1"  method= "POST"  enctype= "multipart /form-data ">

That is, this enctype, the encoding method to add Multipart/form-data, which shows that the binary form of transmission of data (that is, without encoding processing).

If you consider security, you also have to restrict the MIME (Multipurpose Internet Mail Extensions, which describes the Internet content type), for example, the background only accepts MIME-type images (image/jpeg).

Of course, this is not very safe, I now think it is more secure, after receiving files in the background, truncated suffix name, and specify a suffix to the specified folder, so that even if someone uploads the executable file, the suffix changed, the folder does not give execution permissions, it is more secure.

Struts.xml Configuration

<Actionname= "Student_uploadclasschedule"class= "Com.studentweb.action.StudentAction"Method= "Uploadclasschedule">    <!--The following sentence can be used to determine the MIME type -    <paramname= "Fileupload.allowedtypes">Text/plain</param>    <!--Specify file Save path -    <paramname= "Savepath">Classchedule</param>    <resultname= "SUCCESS"type= "Redirect">Student_showclasschedule.do</result></Action>

Action Handling

     PublicString Uploadclasschedule () {uploadfile (file); //The following sentences are just database processing, do not care, filenames and so on must be stored in the database. Classchedule cs =NewClasschedule ();        Cs.setfilename (Filefilename);        Std.addclasschedule (CS); returnSUCCESS; }     Public voiduploadfile (file file) {/**
* The Getrealpath method is to get the absolute path of the storage location, Savapath is configured in the Struts.xml.
* File.separator is the separator for the operating system, Linux/unix---"/", Windows---"\ \"
*/ FinalString Dstpath = Servletactioncontext.getservletcontext (). Getrealpath ( This. Getsavepath ()) +File.separator+Filefilename; Try {
Actually save the file locally is this sentence. Fileutils.copyfile (file,NewFile (Dstpath)); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } PublicString Getsavepath () {returnSavepath; }
Here is the download

Struts.xml Configuration

<Actionname= "Student_downloadcs"class= "Com.studentweb.action.StudentAction"Method= "Downloadcs">     <resultname= "Success"type= "Stream">
<!--here to set the MIME type of the download file, here is the docx type, which requires a self-search configuration. You can also set the encoding--<paramname= "ContentType">Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=iso-8859-1</param>
<!--the source stream for the downloaded file, which corresponds to a property name of type InputStream in the action class, for example a property with a value of targetfile needs to write a Gettargetfile () method--<paramname= "InputName">TargetFile</param>
<!--attachment This setting reminds the browser to pop up the download or open the box directly, FileName returns the processed file name (fix Chinese garbled)--<paramname= "Contentdisposition">Attachment;filename= "${filename}"</param> <paramname= "BufferSize">4096</param> </result></Action>

Background processing

     PublicString Downloadcs () {returnSUCCESS; }         PublicInputStream Gettargetfile () {String Savepath= "Classchedule"; String Temp= Request.getparameter ("filename"); Savepath+ = File.separator +temp;
That is, in the form of a streamreturnServletactioncontext.getservletcontext (). getResourceAsStream (Savepath); } PublicString GetFileName () {
Accept the file name that you want to download String temp= Request.getparameter ("filename"); Try{Temp=NewString (Temp.getbytes (), "iso-8859-1");//troubleshoot Chinese characters when downloading}Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } returntemp; }

By the way, delete it, the main use is Java.io.File.File inside the method.

Background processing, accept the file ID deletion way.

     Publicstring Deletecs () {String temp= Request.getparameter ("id"); intID =integer.valueof (temp);
Here's the information in the database. String filename=std.getfile (ID); Std.deletefile (ID);
Here is the deletion of the actual stored file. String Dstpath= Servletactioncontext.getservletcontext (). Getrealpath ("/classchedule") +File.separator+filename; File File=NewFile (Dstpath); System.out.println (Dstpath+"////"+file.exists ()); if(File.exists ()) File.delete (); return"DeleteFile"; }
/** File Common methods
* File.exists () determine if the file exists
* File.delete () Delete files
* File.getparentfile (). Mkdirs () Create a directory in the upper-level file
* File.createnewfile () Create the current file (in storage)
*/

Struts implements file uploads and downloads.

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.