上傳圖片全部代碼java web上傳圖片代碼

求JAVA上傳圖片代碼

package com;

成都做網(wǎng)站、網(wǎng)站制作服務(wù)團(tuán)隊(duì)是一支充滿著熱情的團(tuán)隊(duì),執(zhí)著、敏銳、追求更好,是創(chuàng)新互聯(lián)的標(biāo)準(zhǔn)與要求,同時(shí)竭誠(chéng)為客戶提供服務(wù)是我們的理念。創(chuàng)新互聯(lián)公司把每個(gè)網(wǎng)站當(dāng)做一個(gè)產(chǎn)品來(lái)開(kāi)發(fā),精雕細(xì)琢,追求一名工匠心中的細(xì)致,我們更用心!

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;

import com.jspsmart.upload.*;

public class uploadfiles extends HttpServlet

{

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException

{

//使用了一個(gè)第三方的組件,存放在web-inf/lib下

response.setContentType("text/html;charset=GB2312");

//由于SmartUpload的初始化方法需要pageContext,所以我們?cè)趕ervlet中得到他

//為了得到pageConext要首先得到JspFactory的實(shí)例

//通過(guò)JspFactory的實(shí)例的getPageContext方法得到pageConext的實(shí)例

JspFactory jf = null;

//得到JspFactory的實(shí)例

jf=JspFactory.getDefaultFactory();

/*

getPageContext(Servlet servlet,

ServletRequest request,

ServletResponse response,

java.lang.String errorPageURL,

boolean needsSession,

int buffer,

boolean autoflush)

*/

PageContext pageContext=jf.getPageContext(this,request,response,null,true,8192,true);

try

{

//實(shí)例化SmartUpload

SmartUpload mySmartUpload=new SmartUpload();

//初始化SmartUpload的實(shí)例,需要PageContext的實(shí)例

mySmartUpload.initialize(pageContext);

//設(shè)定最大上傳的字節(jié)數(shù),其實(shí)可以不進(jìn)行設(shè)定,表示上傳的文件沒(méi)有大小限制

//mySmartUpload.setTotalMaxFileSize(10000000);

mySmartUpload.upload();

//下面是單文件上傳

//上傳的文件以com.jspsmart.upload.File 代表,如果文件名稱重復(fù),則進(jìn)行覆蓋

com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);

String upLoadFileName=file.getFileName();

//調(diào)用com.jspsmart.upload.File實(shí)例的saveas的方法保存文件,此時(shí)的文件名即是

//保存到服務(wù)器上的文件名

file.saveAs("/upload/"+upLoadFileName);

Request req =

Text t = .....;

t.setUpload(upLoadFileName);

t.set.....(req);

}

catch(SmartUploadException e)

{

System.out.println(e.getMessage());

}

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, java.io.IOException

{

doGet(request,response);

}

}

java怎樣上傳圖片(寫(xiě)個(gè)例子謝謝);

我有一段上傳圖片的代碼,并且可以根據(jù)實(shí)際,按月或按天等,生成存放圖片的文件夾

首先在JSP上放一個(gè)FILE的標(biāo)簽這些我都不說(shuō)了,你也一定明白,我直接把處理過(guò)程給你發(fā)過(guò)去

我把其中存到數(shù)據(jù)庫(kù)中的內(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)保證在根目錄中有此目錄的存在 如果沒(méi)有,下面則上創(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()//返回頁(yè)面

}

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);

if (myFile.isMissing()){ //沒(méi)有選擇圖片做提示!

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{

//我上面說(shuō)到,把操作數(shù)據(jù)庫(kù)的代友刪除了,這里就應(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)換大小寫(xiě)

saveurl=request.getRealPath("/")+url;

saveurl+=filename+"."+ext; //保存路徑

myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);

//將圖片信息插入到數(shù)據(jù)庫(kù)中

// ------上傳完成,開(kāi)始生成縮略圖-----

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ì)算新圖長(zhǎng)寬

new_w=150;

new_h=110;//計(jì)算新圖長(zhǎng)寬

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("('上傳文件大小不能超過(guò)"+(file_size_max/1000)+"K');");

}

}else{

returnflag = 2;

}

}

response.sendRedirect();

return "11";

}

java圖片批量上傳代碼?

用struts也可以實(shí)現(xiàn) 多文件上傳

下面是我寫(xiě)的代碼,作為參考!

/*文件目錄*/

public static String [] fileArray={

"logo.png",

"index.swf",

"OEMInfo.txt",

"favicon.ico"};

/**

* @author Caoshun

* @see 接收并保存文件

* */

public static void receiveAndSaveAllFileByPath(ActionForm form,String rootPath1,String rootPath2){

String fileName="";

//獲取表單中的文件資源

HashtableObject, Object files = form.getMultipartRequestHandler().getFileElements();

//遍歷文件,并且循環(huán)保存

//當(dāng)前處理文件序號(hào)

int file_num=1;

for (EnumerationObject e = files.keys(); e.hasMoreElements();) {

/*根據(jù)處理的當(dāng)前文件下標(biāo),確定文件名*/

fileName=fileArray[file_num-1];

FormFile file = (FormFile) files.get((String) e.nextElement());

if (file != null file.getFileSize() 0) {

try {

//使用formfile.getInputStream()來(lái)獲取一個(gè)文件的輸入流進(jìn)行保存。

//文件名

//String fileName = file.getFileName();

//System.out.println("debug in AddEnterpriceAction.java on line 152 fileName is : "+fileName);

//文件大小

//int fileSize = file.getFileSize();

//文件流

InputStream is = file.getInputStream();

//將輸入流保存到文件

//String rootPath = this.servlet.getServletContext().getRealPath("files");

//往cn中寫(xiě)入

File rf = new File(rootPath1);

FileOutputStream fos = null;

fos = new FileOutputStream(new File(rf, fileName));

byte[] b = new byte[10240];

int real = 0;

real = is.read(b);

while (real 0) {

fos.write(b, 0, real);

real = is.read(b);

}

//往en中寫(xiě)入

File rf2 = new File(rootPath2);

InputStream is2 = file.getInputStream();

FileOutputStream fos2 = null;

fos2 = new FileOutputStream(new File(rf2, fileName));

byte[] b2 = new byte[10240];

int real2 = 0;

real2 = is2.read(b2);

while (real2 0) {

fos2.write(b2, 0, real2);

real2 = is2.read(b2);

}

//關(guān)閉文件流

fos.close();

is.close();

fos2.close();

is2.close();

} catch (RuntimeException e1) {

e1.printStackTrace();

} catch (Exception ee) {

ee.printStackTrace();

}

file.destroy();

}

file_num++;

}

}

java實(shí)現(xiàn)圖片上傳至服務(wù)器并顯示,如何做?希望要具體的代碼實(shí)現(xiàn)

很簡(jiǎn)單。

可以手寫(xiě)IO讀寫(xiě)(有點(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("無(wú)法訪問(wèn)存儲(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("無(wú)法創(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);

//超過(guò)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)如下問(wè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)如下問(wèn)題:");

e.printStackTrace(out);

return;

}

finally //總是立即刪除保存表單字段內(nèi)容的臨時(shí)文件

{

fi.delete();

}

}

}

注意 JSP頁(yè)面的form要加enctype="multipart/form-data" 屬性, 提交的時(shí)候要向服務(wù)器說(shuō)明一下 此頁(yè)面包含文件。

如果 還是麻煩,干脆使用Struts 的上傳組件 他對(duì)FileUpload又做了封裝,使用起來(lái)更傻瓜化,很容易掌握。

-----------------------------

以上回答,如有不明白可以聯(lián)系我。

網(wǎng)頁(yè)名稱:上傳圖片全部代碼java web上傳圖片代碼
轉(zhuǎn)載來(lái)源:http://muchs.cn/article32/dosdspc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、App開(kāi)發(fā)、標(biāo)簽優(yōu)化、網(wǎng)站營(yíng)銷移動(dòng)網(wǎng)站建設(shè)、App設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作