檔案上傳
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'uploat.jsp' starting page</title> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadServlet3" enctype="multipart/form-data" method="post"> 上傳使用者:<input type="text" name="username"><br/> 上傳檔案:<input type="file" name="file1"><br/> 上傳檔案:<input type="file" name="file2"><br/> <input type="submit" value="上傳"> </form> </body> </html>
UploadServlet2.java
package cn.xwy.web.servlet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
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;
public class UploadServlet2 extends HttpServlet {
//處理上傳資料
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
if(item.isFormField()){
//為普通輸入項
String inputName = item.getFieldName();
String inputValue = item.getString();
System.out.println(inputName + "=" + inputValue);
}else{
//代表當前出來的item裡面分裝的是上傳檔案
String filename = item.getName().substring(item.getName().lastIndexOf("\\")+1);
InputStream in = item.getInputStream();
int len = 0;
byte buffer[] = new byte[1024];
FileOutputStream out = new FileOutputStream("d:\\" + filename);
while((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
//建立解析工廠
//建立解析器
//呼叫解析器解析request,得到儲存了所有上傳資料的list
//迭代list集合,拿到分裝了每個輸入項filename
//判斷item的型別,如果是普通欄位,則直接獲取資料,如果為上傳檔案,則呼叫留獲取資料寫到本地硬碟
相關文章
- php檔案上傳之多檔案上傳PHP
- 單個檔案上傳和批量檔案上傳
- SpringMVC 單檔案上傳與多檔案上傳SpringMVC
- 檔案上傳之三基於flash的檔案上傳
- Flask——檔案上傳Flask
- PHP上傳檔案PHP
- JavaScript 檔案上傳JavaScript
- Git上傳檔案Git
- YII檔案上傳
- 檔案上傳概述
- beego上傳檔案Go
- 上傳檔案流程
- 上傳EXCLE檔案
- PHP 檔案上傳PHP
- 檔案上傳漏洞
- MVC檔案上傳 - 使用Request.Files上傳多個檔案MVC
- Django檔案上傳 -- 適用於單一小檔案上傳Django
- 上傳檔案的陷阱
- HTTP檔案上傳原理HTTP
- 上傳檔案專題
- PHP 分片上傳檔案PHP
- Java Web 檔案上傳JavaWeb
- WEB漏洞——檔案上傳Web
- Aliyun Oss 上傳檔案
- 使用fileinput上傳檔案
- PHP ftp上傳檔案PHPFTP
- 上傳檔案至GitHubGithub
- 檔案上傳測試
- Linux上傳檔案Linux
- 檔案上傳下載
- laravel 多檔案上傳Laravel
- ajaxfileupload 檔案上傳
- Ajax 之檔案上傳
- SpringMvc檔案上傳SpringMVC
- PHP--檔案上傳PHP
- vc++上傳檔案C++
- Nodejs檔案上傳NodeJS
- Spring上傳檔案Spring