File upload and download
front desk:
1. Submission method: post
2. There are file uploaded form items in the form: <input type="file" />
3. Specify the form type:
Default type: enctype="application/x-www-form-urlencoded"
File upload type: multipart/form-data
FileUpload
It is commonly used in the development of file upload function, and apache also provides file upload components!
FileUpload component:
1. Download the source code
2. Introduce jar files in the project
commons-fileupload-1.2.1.jar [File upload component core jar package]
commons-io-1.4.jar [Embroidery related tool classes for file processing]
use:
public class UploadServlet extends HttpServlet {// upload directory, save the uploaded resources public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/************ File upload component: Handle file upload*******************/try {// 1. File upload factory FileItemFactory factory = new DiskFileItemFactory();// 2. Create file upload core tool class ServletFileUpload upload = new ServletFileUpload(factory);// 1. Set the maximum size allowed for a single file: 30Mupload.setFileSizeMax(30*1024*1024);// 2. Set the total size allowed for file upload form: 80Mupload.setSizeMax(80*1024*1024);// 3. Set the encoding of the file name of the upload form // equivalent to: request.setCharacterEncoding("UTF-8"); upload.setHeaderEncoding("UTF-8");// 3. Determine: Whether the current form is a file upload form if (upload.isMultipartContent(request)){// 4. Convert the requested data into FileItem objects, and then encapsulate List<FileItem> list = upload.parseRequest(request);// traversal: Get each uploaded data for (FileItem item: list){// Judgment: Normal text data if (item.isFormField()){// Normal text data String fieldName = item.getFieldName(); // Form element name String content = item.getString(); // Form element name, corresponding data //item.getString("UTF-8"); Specify the encoding System.out.println(fieldName + " " + content);}// Upload file (file stream) ---> Upload to the upload directory else {// Normal text data String fieldName = item.getFieldName(); // Form element name String name = item.getName(); // File name String content = item.getString(); // Form element name, corresponding data String type = item.getContentType(); // File type InputStream in = item.getInputStream(); // Upload file stream/** 4. File name rename* For different users readme.txt files, do not want to be overwritten! * Background processing: Add a unique tag to the user!*/// a. Randomly generate a unique tag String id = UUID.randomUUID().toString();// b. Splice name with file name = id +"#"+ name;// Get the upload base path String path = getServletContext().getRealPath("/upload");// Create the target file File file = new File(path,name);// Tool class, file upload item.write(file); Item.delete(); // Delete the temporary file generated by the system System.out.println();}}}else {System.out.println("The current form is not a file upload form, processing failed!");}} catch (Exception e) {e.printStackTrace();}}// Manual implementation of the process private void upload(HttpServletRequest request) throws IOException,UnsupportedEncodingException {/*request.getParameter(""); // GET/POSTrequest.getQueryString(); // Get the data submitted by GET request.getInputStream(); // Get the data submitted by post*//****************** Manually get file upload form data****************///1. Get form data stream InputStream in = request.getInputStream();//2. Convert stream InputStreamReader inStream = new InputStreamReader(in, "UTF-8");//3. BufferedReader reader = new BufferedReader(inStream);// Output data String str = null;while ((str = reader.readLine()) != null) {System.out.println(str);}// Close reader.close();inStream.close();in.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}Case:
Index.jsp
<body> <a href="${pageContext.request.contextPath }/upload.jsp">File Upload</a> <a href="${pageContext.request.contextPath }/fileServlet?method=downList">File Download</a> </body>Upload.jsp
<body> <form name="frm_test" action="${pageContext.request.contextPath }/fileServlet?method=upload" method="post" enctype="multipart/form-data"><%--<input type="hidden" name="method" value="upload">--%>Username: <input type="text" name="userName"> <br/>File: <input type="file" name="file_img"> <br/>Input type="submit" value="submit"></form></body>FileServlet.Java
/*** Process file upload and download* @author Jie.Yuan**/public class FileServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Get request parameters: distinguish different operation types String method = request.getParameter("method");if ("upload".equals(method)) {// Upload upload(request,response);}else if ("downList".equals(method)) {// Enter the download list downList(request,response);}else if ("down".equals(method)) {// Download down(request,response);}}/*** 1. Upload */private void upload(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try {// 1. Create factory object FileItemFactory factory = new DiskFileItemFactory();// 2. File upload core tool class ServletFileUpload upload = new ServletFileUpload(factory);// Set size limit parameters upload.setFileSizeMax(10*1024*1024); // Single file size limit upload.setSizeMax(50*1024*1024); // Total file size limit upload.setHeaderEncoding("UTF-8"); // Processing Chinese file encoding// Judge if (upload.isMultipartContent(request)) {// 3. Convert request data to list collection List<FileItem> list = upload.parseRequest(request);// traversal for (FileItem item : list){// Judgment: Normal text data if (item.isFormField()){// Get the name String name = item.getFieldName();// Get the value String value = item.getString();System.out.println(value);} // File form item else {/************ File upload****************/// a. Get the file name String name = item.getName();// ---handle the problem of uploading file name duplicate---// a1. Get the unique mark String id = UUID.randomUUID().toString();// a2. Splice file name name = id + "#" + name; // b. Get the upload directory String basePath = getServletContext().getRealPath("/upload");// c. Create the file object to be uploaded File file = new File(basePath,name);// d. Upload item.write(file);item.delete(); // Delete the temporary file generated when the component is running}}}}} catch (Exception e) {e.printStackTrace();}}/*** 2. Enter the download list */private void downList(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Implementation idea: first get the file names of all files in the upload directory, and then save; jump to the down.jsp list to display //1. Initialize the map collection Map<file name containing unique tags, short file name> ;Map<String,String> fileNames = new HashMap<String,String>();//2. Get the upload directory and the file names of all files under String bathPath = getServletContext().getRealPath("/upload");// Directory File file = new File(bathPath);// In the directory, all file names String list[] = file.list();// Traversal, encapsulate if (list != null && list.length > 0){for (int i=0; i<list.length; i++){// Full name String fileName = list[i];// Short name String shortName = fileName.substring(fileName.lastIndexOf("#")+1);// Encapsulate fileNames.put(fileName, shortName);}}// 3. Save to request domain request.setAttribute("fileNames", fileNames);// 4. Forward request.getRequestDispatcher("/downlist.jsp").forward(request, response);}/*** 3. Handle downloads*/private void down(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// Get the file name downloaded by the user (append data after the url address, get)String fileName = request.getParameter("fileName");fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");// Get the upload directory path String basePath = getServletContext().getRealPath("/upload");// Get a file stream InputStream in = new FileInputStream(new File(basePath,fileName));// If the file name is Chinese, url encoding needs to be performed fileName = URLEncoder.encode(fileName, "UTF-8");// Set the response header for download.setHeader("content-disposition", "attachment;fileName=" + fileName);// Get response byte stream OutputStream out = response.getOutputStream();byte[] b = new byte[1024];int len = -1;while ((len = in.read(b)) != -1){out.write(b, 0, len);}// Close out.close(); in.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}Mail Development
Preparation work, environment construction:
1. Build a mail server locally
Easymail server, eyoumailserversetup.exe
2. Create a new email account
Zhang San sent an email to Li Si.
Step 1:
Create a new domain name: Tools, Server settings, enter itcast.com in the single domain name box
Step 2:
Create a new email account: [email protected]
3. Install foxmail
Configure the email sending server (smtp): localhost 25
Email receiving server (pop3): localhost 110
Create a new account and you can receive emails!
Notice
Notice
If it is a web project, because Javaee comes with email function, there may be problems!
We need to use our own mail.jar file function! You need to delete the mail package in javaee!
use:
For JavaMail development, first introduce jar files:
activation.jar [If you use jdk1.6 or above, you can not use this jar file] mail.jar [Send core package by email]/*** 1. Send a normal email* @author Jie.Yuan**/public class App_SendMail {@Testpublic void testSend() throws Exception {//0. Mail parameters Properties prop = new Properties();prop.put("mail.transport.protocol", "smtp"); // Specify the protocol prop.put("mail.smtp.host", "localhost"); // Host stmp.qq.comprop.put("mail.smtp.port", 25); // Port prop.put("mail.smtp.auth", "true"); // User password authentication prop.put("mail.debug", "true"); // Debug mode//1. Create a session of a mail Session session = Session.getDefaultInstance(prop);//2. Create a mail body object (whole email object) MimeMessage message = new MimeMessage(session);//3. Set mail body parameters: //3.1 Title message.setSubject("My first email");//3.2 Email sending time message.setSentDate(new Date());//3.3 Sender message.setSender(new InternetAddress("[email protected]"));//3.4 Receiver message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));//3.5 Content message.setText("Hello, it has been sent successfully! Text..."); // Simple plain text email message.saveChanges(); // Save email (optional)//4. Send Transport transfer = session.getTransport();trans.connect("zhangsan", "888");// Send mail to trans.sendMessage(message, message.getAllRecipients());trans.close();}}With pictures
/*** Email with image resources* @author Jie.Yuan**/public class App_2SendWithImg {// Initialization parameters private static Properties prop;// Sender private static InternetAddress sendMan = null;static {prop = new Properties();prop.put("mail.transport.protocol", "smtp"); // Specify the protocol prop.put("mail.smtp.host", "localhost"); // Host stmp.qq.comprop.put("mail.smtp.port", 25); // Specify the protocol prop.put("mail.smtp.port", 25); // Specify the protocol prop.put("mail.smtp.port", "localhost"); // Host stmp.qq.comprop.put("mail.smtp.port", 25); // Port prop.put("mail.smtp.auth", "true"); // User password authentication prop.put("mail.debug", "true"); // Debug mode try {sendMan = new InternetAddress("[email protected]");} catch (AddressException e) {throw new RuntimeException(e);}}@Testpublic void testSend() throws Exception {// 1. Create a mail session Session session = Session.getDefaultInstance(prop);// 2. Create a mail object MimeMessage message = new MimeMessage(session);// 3. Set parameters: title, sender, recipient, send time, content message.setSubject("with picture mail"); message.setSender(sendMan); message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); message.setSentDate(new Date());/************************ Set email content: Multifunction user email (related)**********************/// 4.1 Build a multifunctional email block MimeMultipart related = new MimeMultipart("related");// 4.2 Build multi-function mail block content = text on the left + image resource on the right MimeBodyPart content = new MimeBodyPart();MimeBodyPart resource = new MimeBodyPart();// Set specific content: a. Resource (picture)String filePath = App_2SendWithImg.class.getResource("8.jpg").getPath();DataSource ds = new FileDataSource(new File(filePath));DataHandler handler = new DataHandler(ds);resource.setDataHandler(handler);resource.setContentID("8.jpg"); // Set the resource name and reference the foreign key // Set the specific content: b. Text content.setContent("<img src='cid:8.jpg'/> OK! ", "text/html;charset=UTF-8");related.addBodyPart(content);related.addBodyPart(resource);/*********4.3 Add the built complex emails to the emails*******/message.setContent(related);// 5. Send Transport trans = session.getTransport();trans.connect("zhangsan", "888");trans.sendMessage(message, message.getAllRecipients());trans.close();}}Pictures + attachments
/*** 3. Email with image resources and attachments* @author Jie.Yuan**/public class App_3ImgAndAtta {// Initialization parameters private static Properties prop;// Sender private static InternetAddress sendMan = null;static {prop = new Properties();prop.put("mail.transport.protocol", "smtp"); // Specify the protocol prop.put("mail.smtp.host", "localhost"); // Host stmp.qq.comprop.put("mail.smtp.port", 25); // Port prop.put("mail.smtp.auth", "true"); // User password authentication prop.put("mail.debug", "true"); // Debug mode try {sendMan = new InternetAddress("[email protected]");} catch (AddressException e) {throw new RuntimeException(e);}}@Testpublic void testSend() throws Exception {// 1. Create a mail session Session session = Session.getDefaultInstance(prop);// 2. Create a mail object MimeMessage message = new MimeMessage(session);// 3. Set parameters: title, sender, recipient, send time, content message.setSubject("Mail with picture"); message.setSender(sendMan); message.setRecipient(RecipientType.TO, new InternetAddress("[email protected]")); message.setSentDate(new Date());/** Mail development with attachment (picture)*/// Construct a total mail block MimeMultipart mixed = new MimeMultipart("mixed");// --> Total mail is fast, set to message.setContent(mixed);// Left: (Text + Image Resource) MimeBodyPart left = new MimeBodyPart();// Right: Attachment MimeBodyPart right = new MimeBodyPart();// Set to total mail block mixed.addBodyPart(left); mixed.addBodyPart(right);/******* Attachment**********/String attr_path = this.getClass().getResource("a.docx").getPath();DataSource attr_ds = new FileDataSource(new File(attr_path));DataHandler attr_handler = new DataHandler(attr_ds);right.setDataHandler(attr_handler);right.setFileName("a.docx");/************************ Set email content: Multifunction user email (related)**********************/// 4.1 Build a multifunction email block MimeMultipart related = new MimeMultipart("related");// ---> Set to the left.setContent(related);// 4.2 Build the multi-functional mail block content = text on the left + image resource on the right MimeBodyPart content = new MimeBodyPart();MimeBodyPart resource = new MimeBodyPart();// Set specific content: a. Resource (picture)String filePath = App_3ImgAndAtta.class.getResource("8.jpg").getPath();DataSource ds = new FileDataSource(new File(filePath));DataHandler handler = new DataHandler(ds);resource.setDataHandler(handler);resource.setContentID("8.jpg"); // Set the resource name and reference the foreign key // Set the specific content: b. Text content.setContent("<img src='cid:8.jpg'/> OK! ", "text/html;charset=UTF-8");related.addBodyPart(content);related.addBodyPart(resource);// 5. SendTransport trans = session.getTransport();trans.connect("zhangsan", "888");trans.sendMessage(message, message.getAllRecipients());trans.close();}}The above is the example code for uploading and downloading Java files and sending and receiving emails introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!