十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
很簡單。
創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:做網(wǎng)站、網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的榮成網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
可以手寫IO讀寫(有點(diǎn)麻煩)。
怕麻煩的話使用FileUpload組件 在servlet里doPost嵌入一下代碼
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();
//設(shè)置保存上傳文件的目錄
String uploadDir =getServletContext().getRealPath("/up");
System.out.println(uploadDir);
if (uploadDir == null)
{
out.println("無法訪問存儲(chǔ)目錄!");
return;
}
//根據(jù)路徑創(chuàng)建一個(gè)文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目錄不存在 創(chuàng)建一個(gè) 不能創(chuàng)建輸出...
{
out.println("無法創(chuàng)建存儲(chǔ)目錄!");
return;
}
}
if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能處理multipart/form-data類型的數(shù)據(jù)!");
return ;
}
DiskFileUpload fu = new DiskFileUpload();
//最多上傳200M數(shù)據(jù)
fu.setSizeMax(1024 * 1024 * 200);
//超過1M的字段數(shù)據(jù)采用臨時(shí)文件緩存
fu.setSizeThreshold(1024 * 1024);
//采用默認(rèn)的臨時(shí)文件存儲(chǔ)位置
//fu.setRepositoryPath(...);
//設(shè)置上傳的普通字段的名稱和文件字段的文件名所采用的字符集編碼
fu.setHeaderEncoding("gb2312");
//得到所有表單字段對(duì)象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request對(duì)象中上傳的文件
}
catch (FileUploadException e)
{
out.println("解析數(shù)據(jù)時(shí)出現(xiàn)如下問題:");
e.printStackTrace(out);
return;
}
//處理每個(gè)表單字段
Iterator i = fileItems.iterator();
while (i.hasNext())
{
FileItem fi = (FileItem) i.next();
if (fi.isFormField()){
String content = fi.getString("GB2312");
String fieldName = fi.getFieldName();
request.setAttribute(fieldName,content);
}else{
try
{
String pathSrc = fi.getName();
if(pathSrc.trim().equals("")){
continue;
}
int start = pathSrc.lastIndexOf('\\');
String fileName = pathSrc.substring(start + 1);
File pathDest = new File(uploadDir, fileName);
fi.write(pathDest);
String fieldName = fi.getFieldName();
request.setAttribute(fieldName, fileName);
}catch (Exception e){
out.println("存儲(chǔ)文件時(shí)出現(xiàn)如下問題:");
e.printStackTrace(out);
return;
}
finally //總是立即刪除保存表單字段內(nèi)容的臨時(shí)文件
{
fi.delete();
}
}
}
注意 JSP頁面的form要加enctype="multipart/form-data" 屬性, 提交的時(shí)候要向服務(wù)器說明一下 此頁面包含文件。
如果 還是麻煩,干脆使用Struts 的上傳組件 他對(duì)FileUpload又做了封裝,使用起來更傻瓜化,很容易掌握。
-----------------------------
以上回答,如有不明白可以聯(lián)系我。
java web開發(fā)中,使用文件操作類來上傳圖片并讀取,如下代碼:
*?@desc:?圖片處理工具
*?@author:?bingye
*?@createTime:?2015-3-17?下午04:25:32
*?@version:?v1.0
*/
public?class?ImageUtil?{
/**
*?將圖片寫到客戶端
*?@author:?bingye
*?@createTime:?2015-3-17?下午04:36:04
*?@history:
*?@param?image
*?@param?response?void
*/
public?static?void?writeImage(byte[]?image,HttpServletResponse?response){
if(image==null){
return;
}
byte[]?buffer=new?byte[1024];
InputStream?is=null;
OutputStream?os=null;
try?{
is=new?ByteArrayInputStream(image);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally{
try?{
if(is!=null){is.close();}
if(os!=null){os.close();}
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
}
/**
*?獲取指定路勁圖片
*?@author:?bingye
*?@createTime:?2015-3-21?上午10:50:44
*?@param?filePath
*?@param?response?void
*/
public?static?void?writeImage(String?filePath,HttpServletResponse?response){
File?imageFile=new?File(filePath);?
if(imageFile!=null??imageFile.exists()){
byte[]?buffer=new?byte[1024];
InputStream?is=null;
OutputStream?os=null;
try?{
is=new?FileInputStream(imageFile);
os=response.getOutputStream();
while(is.read(buffer)!=-1){
os.write(buffer);
os.flush();
}
}?catch?(FileNotFoundException?e)?{
e.printStackTrace();
}?catch?(IOException?e)?{
e.printStackTrace();
}?finally{
try?{
if(is!=null){is.close();}
if(os!=null){os.close();}
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
}
}
/**
*?圖片上傳到文件夾
*?@author:?bingye
*?@createTime:?2015-3-20?下午08:07:25
*?@param?file
*?@param?savePath
*?@return?boolean
*/
public?static?ResultDto?uploadToLocal(CommonsMultipartFile?file,String?savePath){
if(file!=null??!file.isEmpty()){
//獲取文件名稱
String?fileName=file.getOriginalFilename();
//獲取后綴名
String?suffixName=fileName.substring(fileName.indexOf(".")+1);
//新名稱
String?newFileName=System.currentTimeMillis()+"."+suffixName;
//新文件路勁
String?filePath=savePath+newFileName;
//獲取存儲(chǔ)文件路徑
File?fileDir=new?File(savePath);
if(!fileDir.exists()){
//如果文件夾沒有:新建
fileDir.mkdirs();
}
FileOutputStream?fos=null;
try?{
fos=new?FileOutputStream(filePath);
fos.write(file.getBytes());
fos.flush();
return?ResultUtil.success("UPLOAD_SUCCESS",?URLEncoder.encode(newFileName,"utf-8"));
}?catch?(Exception?e)?{
e.printStackTrace();
return?ResultUtil.fail("UPLOAD_ERROR");
}?finally{
try?{
if(fos!=null){
fos.close();
}
}?catch?(IOException?e)?{
e.printStackTrace();
return?ResultUtil.fail("UPLOAD_ERROR");
}
}
}
return?ResultUtil.fail("UPLOAD_ERROR");
}
}
我們使用一些已有的組件幫助我們實(shí)現(xiàn)這種上傳功能。
常用的上傳組件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload為例講解
1、在jsp端
form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"
要注意enctype="multipart/form-data"
然后只需要放置一個(gè)file控件,并執(zhí)行submit操作即可
input name="file" type="file" size="20"
input type="submit" name="submit" value="提交"
2、web端
核心代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表單參數(shù)名:" + item.getFieldName() + ",表單參數(shù)值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null !item.getName().equals("")) {
System.out.println("上傳文件的大小:" + item.getSize());
System.out.println("上傳文件的類型:" + item.getContentType());
System.out.println("上傳文件的名稱:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上傳文件成功!");
}else{
request.setAttribute("upload.message", "沒有選擇上傳文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上傳文件失??!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
我有一段上傳圖片的代碼,并且可以根據(jù)實(shí)際,按月或按天等,生成存放圖片的文件夾
首先在JSP上放一個(gè)FILE的標(biāo)簽這些我都不說了,你也一定明白,我直接把處理過程給你發(fā)過去
我把其中存到數(shù)據(jù)庫中的內(nèi)容刪除了,你改一下就能用
/**
*
* 上傳圖片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/
//這里我是同步上傳的,你隨意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDate()Format formatDate() = new SimpleDate()Format("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //應(yīng)保證在根目錄中有此目錄的存在 如果沒有,下面則上創(chuàng)建新的文件夾
if(!root.isDirectory())
{
System.out.println("創(chuàng)建新文件夾成功"+formatnowtime);
root.mkdir();
}
int returnflag = 0;
SmartUpload mySmartUpload =new SmartUpload();
int file_size_max=1024000;
String ext="";
String url="uploadfile/images/"+formatnowtime+"/";
// 只允許上載此類文件
try{
// 初始化
mySmartUpload.initialize(servlet.getServletConfig(),request,response);
mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");
// 上載文件
mySmartUpload.upload();
} catch (Exception e){
response.sendRedirect()//返回頁面
}
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){ //沒有選擇圖片做提示!
returnflag = 3;
}else{
String myFileName=myFile.getFileName(); //取得上載的文件的文件名
ext= myFile.getFileExt(); //取得后綴名
if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上傳!)
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_sizefile_size_max){
try{
//我上面說到,把操作數(shù)據(jù)庫的代友刪除了,這里就應(yīng)該是判斷,你的圖片是不是已經(jīng)存在了,存在要怎么處理,不存在要怎么處了,就是你的事了 }
//更改文件名,取得當(dāng)前上傳時(shí)間的毫秒數(shù)值
Calendar calendar = Calendar.getInstance();
//String filename = String.valueOf(calendar.getTimeInMillis());
String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");
String filename = did;
String flag = "0";
String path = request.getRealPath("/")+url;
String ename = myFile.getFileExt();
//.toLowerCase()轉(zhuǎn)換大小寫
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路徑
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//將圖片信息插入到數(shù)據(jù)庫中
// ------上傳完成,開始生成縮略圖-----
java.io.File file = new java.io.File(saveurl); //讀入剛才上傳的文件
String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的縮略圖保存地址
Image src = javax.imageio.ImageIO.read(file); //構(gòu)造Image對(duì)象
float tagsize=200;
int old_w=src.getWidth(null);
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0;
int tempsize;
float tempdouble;
if(old_wold_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
// new_w=Math.round(old_w/tempdouble);
// new_h=Math.round(old_h/tempdouble);//計(jì)算新圖長寬
new_w=150;
new_h=110;//計(jì)算新圖長寬
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //繪制縮小后的圖
FileOutputStream newimage=new FileOutputStream(newurl); //輸出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG編碼
newimage.close();
returnflag = 1;
}else{
returnflag = 0;
System.out.println("('上傳文件大小不能超過"+(file_size_max/1000)+"K');");
}
}else{
returnflag = 2;
}
}
response.sendRedirect();
return "11";
}