91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java實現文件上傳下載

發布時間:2020-10-06 04:55:00 來源:腳本之家 閱讀:181 作者:DOLFAMINGO 欄目:編程語言

本文實例為大家分享了java實現文件上傳下載的具體代碼,供大家參考,具體內容如下

一.上傳

1.前端:

<form method="post" action="FileUpload" enctype="multipart/form-data">
  <input type="file" name="uploadFile" />
  <br/>
  <input type="submit" value="上傳" />
</form>

2.后臺:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import dao.FileDao;


@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {
  private static final long serialVersionUID = 1L;
   
  // 上傳配置
  private static final int MEMORY_THRESHOLD  = 1024 * 1024 * 3; // 3MB
  private static final int MAX_FILE_SIZE   = 1024 * 1024 * 40; // 40MB
  private static final int MAX_REQUEST_SIZE  = 1024 * 1024 * 50; // 50MB
  
  public FileUpload() {
    super();
  }
  
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    
      if (!ServletFileUpload.isMultipartContent(request)) {
      // 如果不是則停止
      out.println("Error: 表單必須包含 enctype=multipart/form-data");
      out.flush();
      return;
    }
    
    // 配置上傳參數
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 設置內存臨界值 - 超過后將產生臨時文件并存儲于臨時目錄中
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // 設置臨時存儲目錄
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
    ServletFileUpload upload = new ServletFileUpload(factory);
     
    // 設置最大文件上傳值
    upload.setFileSizeMax(MAX_FILE_SIZE);
     
    // 設置最大請求值 (包含文件和表單數據)
    upload.setSizeMax(MAX_REQUEST_SIZE);
    
    // 中文處理
    upload.setHeaderEncoding("UTF-8"); 
    
    
    String uploadPath = request.getServletContext().getRealPath("/files");
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
      uploadDir.mkdir();
    }
    
    try {
      // 解析請求的內容提取文件數據
      List<FileItem> formItems = upload.parseRequest(request);
      if (formItems != null && formItems.size() > 0) {
        // 迭代表單數據
        for (FileItem item : formItems) {
          // 處理不在表單中的字段
          if (!item.isFormField()) {
            String fileName = new File(item.getName()).getName();
            String filePath = uploadPath + File.separator + fileName;
            File storeFile = new File(filePath);
            // 在控制臺輸出文件的上傳路徑
//            System.out.println(filePath);
            // 保存文件到硬盤
            if(storeFile.exists()) {
              out.println("上傳失敗,文件已存在!");
            }else {
              item.write(storeFile);
              out.println("文件上傳成功!");
            }  
          }
        }
      }
    } catch (Exception ex) {
      response.getWriter().println("文件上傳成功!");
    }
  }

  
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
} 

二.下載

1.下載鏈接:

FileDownload?filename="+URLEncoder.encode(filename,"utf-8") --------- 需要對URL中的中文參數進行編碼,否則會出現亂碼

2.后臺:

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/FileDownload")
public class FileDownload extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  public FileDownload() {
    super();
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    
    String dirPath = request.getServletContext().getRealPath("/files");
    String filename = URLEncoder.encode(request.getParameter("filename"),"utf-8");  //需要對URL中的中文參數進行編碼,否則出現亂碼
    response.getWriter().println(filename);
    String filepath = dirPath + File.separator + filename;
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    FileInputStream fileInputStream = new FileInputStream(filepath);
    int i = 0;
    while ((i = fileInputStream.read()) != -1) {
      out.write(i);
    }
    fileInputStream.close();
    out.close();
  }
  
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

抚州市| 于都县| 会同县| 罗江县| 隆昌县| 潢川县| 普兰店市| 西吉县| 马山县| 河曲县| 手游| 崇阳县| 浮山县| 潮州市| 探索| 抚宁县| 镇平县| 区。| 抚州市| 肇庆市| 白银市| 衡水市| 嘉义县| 甘孜县| 漳州市| 依安县| 齐齐哈尔市| 邻水| 岳阳市| 常山县| 黑龙江省| 高碑店市| 揭阳市| 天长市| 玉屏| 华安县| 塔城市| 石阡县| 陵水| 缙云县| 临颍县|