1. 程式人生 > >Struts的上傳與下載

Struts的上傳與下載

檔案上傳:
1.上傳到資料庫(oa)
2.上傳到檔案伺服器(一般記憶體較大)
3.上傳到普通伺服器(這裡使用tomcat)

  1. 上傳:

例子(普通伺服器 io包):
在這裡插入圖片描述
首先在你的子控制器中宣告這三個變數提供get/set(注意file這個變數名指的是你從jsp頁面跳轉的name,名字對應即可,後面的型別和名字一樣

  • 程式碼
public String upLoad() {
		try {
			StudentDAO studentDAO = new StudentDAO();
			student.setPathname(fileFileName);
			student.setType(fileContentType);
			studentDAO.editFile(student);
			FileUtils.copyFile(file,new File(application.getRealPath("/image/")+fileFileName));
			if(fileFileName!=null&&!"".equals(fileFileName)) {
				return SUCCESS;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	return FAIL;
	
	}

上傳核心:
FileUtils.copyFile(file,new File(application.getRealPath("/image/")+fileFileName));
這裡的file就是我們宣告的file檔案,後面是頁面所在伺服器的路徑
在這裡插入圖片描述
圖片上傳好之後就在這裡了

2 . 下載

jsp:
在這裡插入圖片描述
java:

	public void downLoad() {
		String name=request.getParameter("pathname");
			if(name!=null&&!"".equals(name)) {
				  response.setContentType(request.getParameter("type"));
				  response.setHeader("Content-Disposition","attachment;filename=" +name);//�ļ���
				  try {
					FileUtils.copyFile(new File(application.getRealPath("/image/")+name), response.getOutputStream());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}
  • 步驟:
  1. 內容型別 response.setContentType(d.getMime());

  2. -設定響應頭 response.setHeader(“Content-Disposition”,“attachment;filename=” +
    fileName);//檔名

  3. FileUtils.copyFile(new
    File(application.getRealPath("/image/")+name),
    response.getOutputStream());下載(列如google會將圖片下載到你瀏覽器指定的目錄)