圖片上傳java代碼 java發(fā)送圖片

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

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

成都做網(wǎng)站、成都網(wǎng)站建設(shè),成都做網(wǎng)站公司-成都創(chuàng)新互聯(lián)公司已向上千余家企業(yè)提供了,網(wǎng)站設(shè)計(jì),網(wǎng)站制作,網(wǎng)絡(luò)營銷等服務(wù)!設(shè)計(jì)與技術(shù)結(jié)合,多年網(wǎng)站推廣經(jīng)驗(yàn),合理的價(jià)格為您打造企業(yè)品質(zhì)網(wǎng)站。

首先在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";

}

求JAVA上傳圖片代碼

package com;

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,所以我們在servlet中得到他

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

//通過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è)定,表示上傳的文件沒有大小限制

//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 關(guān)于圖片上傳的代碼

private File file;

private String fileFileName;

private String picture;

//都有g(shù)etter 和 setter

InputStream is = new FileInputStream(file);

//引入一個(gè)IO流的輸入流

String root = ServletActionContext.getRequest()

.getRealPath("/bookpicture");

//通過REQUEST來得到相對(duì)地址,并在后面加上/bookpicture

File f = new File(root, this.getFileFileName());

//定義一個(gè)FILE文件,第一個(gè)參數(shù)是文件的路徑,第二個(gè)是文件的名字

picture="."+"\\"+"bookpicture"+"\\"+this.getFileFileName();

//為PICTURE字符串賦值,/地址/文件名

System.out.println

("======picture====="+picture);

//從控制臺(tái)輸出Picture

OutputStream os = new FileOutputStream(f);

//第一個(gè)文件的輸出流

byte[] buffer = new byte[1024];

//定義一個(gè)bufer的字符串,長度為1024

int len = 0;

while ((len = is.read(buffer)) 0) {

//如果從制定文件中讀取到的信息為結(jié)束就繼續(xù)循環(huán)

os.write(buffer, 0, len);

//將文件讀出的內(nèi)容寫入到指定的文件中

}

app怎么上傳圖片到j(luò)ava后臺(tái)?java后臺(tái)處理的具體代碼是怎么寫的?

使用一些已有的組件幫助我們實(shí)現(xiàn)這種上傳功能。常用的上傳組件:Apache的CommonsFileUploadJavaZoom的UploadBeanjspSmartUpload以下,以FileUpload為例講解1、在jsp端要注意enctype="multipart/form-data"然后只需要放置一個(gè)file控件,并執(zhí)行submit操作即可2、web端核心代碼如下:publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("UTF-8");DiskFileItemFactoryfactory=newDiskFileItemFactory();ServletFileUploadupload=newServletFileUpload(factory);try{Listitems=upload.parseRequest(request);Iteratoritr=items.iterator();while(itr.hasNext()){FileItemitem=(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());FiletempFile=newFile(item.getName());Filefile=newFile(sc.getRealPath("/")+savePath,tempFile.getName());item.write(file);request.setAttribute("upload.message","上傳文件成功!");}else{request.setAttribute("upload.message","沒有選擇上傳文件!");}}}}catch(FileUploadExceptione){e.printStackTrace();}catch(Exceptione){e.printStackTrace();request.setAttribute("upload.message","上傳文件失敗!");}request.getRequestDispatcher("/uploadResult.jsp").forward(request,response);}

怎么用Java實(shí)現(xiàn)圖片上傳

下面這是servlet的內(nèi)容:

package demo;

import java.io.File;

import java.io.IOException;

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.ProgressListener;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class DemoServlet extends HttpServlet {

private static final String UPLOAD_DIRECTORY = "upload";

private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB

private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB

private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

DiskFileItemFactory factory=new DiskFileItemFactory();

ServletFileUpload sfu=new ServletFileUpload(factory);

sfu.setHeaderEncoding("UTF-8");

sfu.setProgressListener(new ProgressListener() {

public void update(long pBytesRead, long pContentLength, int pItems) {

System.out.println("文件大小為:"+pContentLength+",當(dāng)前已處理:"+pBytesRead);

}

});

//判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)

if(!ServletFileUpload.isMultipartContent(request)){

PrintWriter writer= response.getWriter();

writer.println("Error:表單必須包含 enctype=multipart/form-data");

writer.flush();

return;

}

factory.setSizeThreshold(MEMORY_THRESHOLD);

//設(shè)置臨時(shí)儲(chǔ)存目錄

factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

//設(shè)置最大文件上傳值

sfu.setFileSizeMax(MAX_FILE_SIZE);

//設(shè)置最大請(qǐng)求值(包含文件和表單數(shù)據(jù))

sfu.setSizeMax(MAX_REQUEST_SIZE);

String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;

File file=new File(uploadpath);

if(!file.exists()){

file.mkdir();

}

try {

ListFileItem formItems = sfu.parseRequest(request);

if(formItems!=nullformItems.size()0){

for(FileItem item:formItems){

if(!item.isFormField()){

String fileName=new File(item.getName()).getName();

String filePath=uploadpath+File.separator+fileName;

File storeFile=new File(filePath);

System.out.println(filePath);

item.write(storeFile);

request.setAttribute("message", "文件上傳成功!");

}

}

}

} catch (Exception e) {

request.setAttribute("message", "錯(cuò)誤信息:"+e.getMessage());

}

getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);

}

}

下面是jsp的內(nèi)容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉(zhuǎn)發(fā)的路徑改一下:

%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%

!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""

html

head

meta http-equiv="Content-Type" content="text/html; charset=UTF-8"

titleInsert title here/title

/head

body

form action="demo.do" enctype="multipart/form-data" method="post"

input type="file" name="file1" /

%

String message = (String) request.getAttribute("message");

%

%=message%

input type="submit" value="提交"/

/form

/body

/html

這段代碼可以實(shí)現(xiàn)普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳

網(wǎng)頁標(biāo)題:圖片上傳java代碼 java發(fā)送圖片
當(dāng)前URL:http://muchs.cn/article44/docdeee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、企業(yè)網(wǎng)站制作全網(wǎng)營銷推廣、企業(yè)建站、網(wǎng)站內(nèi)鏈自適應(yīng)網(wǎng)站

廣告

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

網(wǎng)站托管運(yùn)營