Jsp file upload and download instance code

Source: Internet
Author: User

File Upload: Copy codeThe Code is as follows: public class UploadServlet extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
DoPost (req, resp );
}
@ Override
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
SmartUpload myupload = new SmartUpload ();
ServletConfig config = getServletConfig ();
Myupload. initialize (config, req, resp );
Resp. setContentType ("text/html ");
Resp. setCharacterEncoding ("UTF-8 ");
PrintWriter out = resp. getWriter ();
Out. println ("Out. println ("

Try {
Myupload. setMaxFileSize (1024*1024 );
Myupload. setTotalMaxFileSize (5*1024*1024 );

Myupload. setAllowedFilesList ("doc, txt, jpg, gif ");
Myupload. setDeniedFilesList ("exe, bat, jsp, htm, html ");
Myupload. upload (); // upload a file. This item is required.
Int count = myupload. getFiles (). getCount ();
Request myRequest = myupload. getRequest ();
String rndFilename, fileExtName, fileName, filePathName;
Date dt = null;
SimpleDateFormat fmt = new SimpleDateFormat ("yyyyMMdd ");
// Extract the uploaded file information one by one, while keeping the file
For (int I = 0; I <count; I ++ ){
File file = myupload. getFiles (). getFile (I );
If (file. isMissing ())
Continue;
FileName = new String (file. getFileName (). getBytes (), "UTF-8"); // get the file name
FilePathName = new String (file. getFilePathName (). getBytes (), "UTF-8 ");
FileExtName = file. getFileExt ();
Dt = new Date (System. currentTimeMillis ());
Thread. sleep (100 );
RndFilename = fmt. format (dt) + I + "." + fileExtName;
Out. println ("no." + (I + 1) + "File Information: <br> ");
Out. println ("file name:" + fileName + "<br> ");
Out. println ("File Extension:" + fileExtName + "<br> ");
Out. println ("file full name:" + filePathName + "<br> ");
Out. println ("file size:" + file. getSize ()/1024 + "kb <br> ");
// Create a file storage location
ServletContext context = req. getServletContext ();
String savePath = context. getRealPath ("/upload /");
Java. io. File folder = new java. io. File (savePath );
If (! Folder. exists ()){
Folder. mkdirs ();
}
Out. println ("file storage path:" + savePath );
File. saveAs (savePath + "/" + rndFilename, SmartUpload. SAVE_PHYSICAL );
}

} Catch (Exception e ){
Out. println ("File Upload Failed !!!! ");
E. printStackTrace ();
}
Out. flush ();
Out. close ();

}
}

Copy codeThe Code is as follows: <% @ page language = "java" contentType = "text/html; charset = UTF-8"
PageEncoding = "UTF-8" %>
<% @ Page import = "com. jspsmart. upload. *" %>
<%
// Set the request encoding method. Otherwise, garbled characters may occur in Chinese.
Request. setCharacterEncoding ("UTF-8 ");
%>
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> upload a file instance </title>
<Script type = "text/javascript" src = "js/jquery-1.8.1.js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ("# Number"). change (function (){
Var number = $ ("# number"). attr ("value ");
$ ("# Files" pai.html ("");
For (var I = 0; I <number; I ++ ){
$ ("# Files"). append ("<input type = 'file' name = 'file'" + I + "'> <br/> ");
}
});
});
</Script>
</Head>
<Body>
<H2> upload a file instance Select the number of uploaded files:
<Select id = "number">
<Option value = "1" selected = "selected"> 1 </option>
<Option value = "2"> 2 </option>
<Option value = "3"> 3 </option>
<Option value = "4"> 4 </option>
<Option value = "5"> 5 </option>
</Select>
<Form action = "UploadServlet" method = "post" enctype = "multipart/form-data">
<Div id = "files"> </div>
<Input type = "submit" value = "submit"/>
</Form>
</Body>
</Html>

File Download:Copy codeThe Code is as follows: <%
Response. setContentType ("application/x-download"); // set it to download application/x-download
String filedownload = "/file name to be downloaded"; // relative path of the file to be downloaded
String filedisplay = "the name of the file to be saved to the user"; // The name of the file to be saved when the file is downloaded
String filenamedisplay = URLEncoder. encode (filedisplay, "UTF-8 ");
Response. addHeader ("Content-Disposition", "attachment; filename =" + filedisplay );
Try
{
RequestDispatcher dis = application. getRequestDispatcher (filedownload );
If (dis! = Null)
{
Dis. forward (request, response );
}
Response. flushBuffer ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
Finally
{
}
%>

Related Article

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.