码迷,mamicode.com
首页 > 其他好文 > 详细

File Upload & Download

时间:2020-06-24 21:55:15      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:enc   imp   catch   tput   servlet   div   version   list   cep   

 

Upload

 


<form method="post" action="http://localhost:8080/thirdTry/uploadServlet"
enctype="multipart/form-data">

 

Profile Image: <input type="file" name="photo"> <br>

// upload.jsp
<%
@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Upload</title> </head> <body> <form method="post" action="http://localhost:8080/thirdTry/uploadServlet" enctype="multipart/form-data"> Username: <input type="text" name="username"/> <br> Profile Image: <input type="file" name="photo"> <br> <input type="submit" value="Submit"> </form> </body> </html>

JAR you need:
      <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.4</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.2.1</version>
      </dependency>

ServletFileUpload class: Parse the uploaded data

 

FileItem class : represents every form item

 

UploadServlet.java

 


 

package com.truman.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String username = req.getParameter("username");
////        System.out.println("Got Request.");
//
//        ServletInputStream inputStream = req.getInputStream();
//
//        byte[] buffer = new byte[1024];
//        int read = inputStream.read(buffer);
//        System.out.println(new String(buffer, 0, read));
        // determine if the data uploaded is multipart/form-data
        if(ServletFileUpload.isMultipartContent(req)){
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //ServletFileUpload is used to parse the data uploaded
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
            // get every form item
                List<FileItem> list = servletFileUpload.parseRequest(req);
                // determine every item : regular file or uploaded file
                for(FileItem fileItem : list){
                    if(fileItem.isFormField()){
                        //regular file
                        System.out.println("attribute is : " + fileItem.getFieldName());
                        System.out.println("value is : " + fileItem.getString("UTF-8"));
                    }else{
                        // the file uploaded
                        System.out.println("attribute is : " + fileItem.getFieldName());
                        System.out.println("File name : " + fileItem.getName());

                        try {
                            fileItem.write(new File("/Users/truman/Desktop/father.jpg"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
        }

    }
}

 

 

 Download

 


 

DownloadServlet.java

package com.truman.servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // get the filename
        String downloadFilename = "nana.jpeg";
        // get the context of the file through servletContext
        ServletContext servletContext = this.getServletContext();

        // tell response type to client
        String mimeType = servletContext.getMimeType("/file/" + downloadFilename);
        resp.setContentType(mimeType);
        // tell client the file is to download, or the browser will just display it
        resp.setHeader("Content-Disposition", "attachment;  filename=" + downloadFilename);
//        URLEncoder.encode("汉字.jpg","UTF-8") : if you use Chinese, use this to replace the filename
        // URLEncoder is used in Chrome and IE, but in Firefox, use Base64

        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFilename);

        // use IOUtils to read all the data and send to output
        OutputStream outputStream = resp.getOutputStream();
        IOUtils.copy(resourceAsStream, outputStream);

    }
}

 

 

 

File Upload & Download

标签:enc   imp   catch   tput   servlet   div   version   list   cep   

原文地址:https://www.cnblogs.com/nedrain/p/13189895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!