pack
創(chuàng)新互聯(lián)建站公司2013年成立,先為弓長嶺等服務建站,弓長嶺等地企業(yè),進行企業(yè)商務咨詢服務。為弓長嶺企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務解決您的所有建站問題。age com.itheima.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import com.itheima.util.IdGenertor;
public class UploadServlet3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//檢測form是否是multipart/form-data類型的
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new RuntimeException("The form's enctype attribute value must be multipart/form-data");
}
//解析請求內(nèi)容
DiskFileItemFactory factory = new DiskFileItemFactory();//產(chǎn)生FileItem的工廠
factory.setRepository(new File("d:/"));//指定臨時文件的存放目錄
ServletFileUpload sfu = new ServletFileUpload(factory);
// sfu.setFileSizeMax(3*1024*1024);//單個文件大小限制
// sfu.setSizeMax(5*1024*1024);//總文件大小
List
items = new ArrayList();
try {
items = sfu.parseRequest(request);
}catch(FileUploadBase.FileSizeLimitExceededException e) {
response.getWriter().write("單個文件不能超過3M");
}
catch(FileUploadBase.SizeLimitExceededException e) {
response.getWriter().write("總文件不能超過5M");
}catch (FileUploadException e) {
e.printStackTrace();
throw new RuntimeException("解析請求失敗");
}
//遍歷:
for(FileItem item:items){
//處理普通字段
if(item.isFormField()){
processFormField(item);
}else{
//處理上傳字段
processUploadField(item);
}
}
}
protected void processUploadField(FileItem item) {
try {
// InputStream in = item.getInputStream();
//找一個存放文件的位置;存放的文件名
String fileName = item.getName();//上傳的文件的文件名 C:UserswzhtingDesktopa.txt a.txt(瀏覽器不同)
if(fileName!=null&&!fileName.equals("")){
//限定上傳文件的類型
if(!item.getContentType().startsWith("image")){
return;
}
fileName = FilenameUtils.getName(fileName);
fileName = IdGenertor.genGUID()+"_"+fileName;
//存放路徑
String realPath = getServletContext().getRealPath("/WEB-INF/files");
//生成一個子目錄
String childDirectory = genChildDirectory(realPath,fileName);
File storeDirectory = new File(realPath+File.separator+childDirectory);
if(!storeDirectory.exists()){
storeDirectory.mkdirs();
}
// OutputStream out = new FileOutputStream(new File(storeDirectory, fileName));
//
// int len = -1;
// byte b[] = new byte[1024];
// while((len=in.read(b))!=-1){
// out.write(b, 0, len);
// }
// in.close();
// out.close();
//
// item.delete();//清除臨時文件
item.write(new File(storeDirectory, fileName));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String genChildDirectory(String realPath, String fileName) {
int hashCode = fileName.hashCode();
int dir1 = hashCode&0xf;
int dir2 = (hashCode&0xf0)>>4;
String str = dir1+File.separator+dir2;
File file = new File(realPath,str);
if(!file.exists()){
file.mkdirs();
}
return str;
}
//按照日期生成子目錄
private String genChildDirectory(String realPath) {
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String str = df.format(now);
File file = new File(realPath,str);
if(!file.exists()){
file.mkdirs();
}
return str;
}
protected void processFormField(FileItem item) {
//打印到控制臺
String fieldName = item.getFieldName();
String fieldValue = "";
try {
fieldValue = item.getString("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(fieldName+"="+fieldValue);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} 做做筆記,傳播知識,我是個勤勞的搬運工
1224144402@qq.com
新聞標題:FileUpload組件-創(chuàng)新互聯(lián)
網(wǎng)頁地址:http://weahome.cn/article/hjoes.html