java上傳圖片前端代碼 前端怎么實(shí)現(xiàn)上傳圖片

java web開發(fā),上傳圖片并讀取

java web開發(fā)中,使用文件操作類來上傳圖片并讀取,如下代碼:

天河網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),天河網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為天河近1000家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)營銷網(wǎng)站建設(shè)要多少錢,請找那個售后服務(wù)好的天河做網(wǎng)站的公司定做!

*?@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;

//獲取存儲文件路徑

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");

}

}

java 圖片上傳

//1.初始化smartupload對象

SmartUpload su=new SmartUpload();

su.initialize(pageContext);

//2.定義上傳文件類型

su.setAllowedFilesList("gif,jpg,doc,txt");

//3.不允許上傳類型

su.setDeniedFilesList("jsp,asp,html,exe,bat");

//4.設(shè)置字符編碼、

su.setCharset("UTF-8");

//5.設(shè)置的單個上傳最大限制

su.setMaxFileSize(5*1024*1024);

//6.總共上傳限制

su.setTotalMaxFileSize(20*1024*1024);

//7.上傳

su.upload();

//su.getFiles().getCount() 獲取上傳數(shù)

File file=su.getFiles().getFile(0);

String filename=file.getFileName();

System.out.print(filename);

String filepath="upload\\";

filepath+=file.getFileName();

file.saveAs(filepath,SmartUpload.SAVE_VIRTUAL);

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

很簡單。

可以手寫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("無法訪問存儲目錄!");

return;

}

//根據(jù)路徑創(chuàng)建一個文件

File fUploadDir = new File(uploadDir);

if(!fUploadDir.exists()){

if(!fUploadDir.mkdir())//如果UP目錄不存在 創(chuàng)建一個 不能創(chuàng)建輸出...

{

out.println("無法創(chuàng)建存儲目錄!");

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ù)采用臨時文件緩存

fu.setSizeThreshold(1024 * 1024);

//采用默認(rèn)的臨時文件存儲位置

//fu.setRepositoryPath(...);

//設(shè)置上傳的普通字段的名稱和文件字段的文件名所采用的字符集編碼

fu.setHeaderEncoding("gb2312");

//得到所有表單字段對象的集合

List fileItems = null;

try

{

fileItems = fu.parseRequest(request);//解析request對象中上傳的文件

}

catch (FileUploadException e)

{

out.println("解析數(shù)據(jù)時出現(xiàn)如下問題:");

e.printStackTrace(out);

return;

}

//處理每個表單字段

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("存儲文件時出現(xiàn)如下問題:");

e.printStackTrace(out);

return;

}

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

{

fi.delete();

}

}

}

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

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

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

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

請問用Java 如何實(shí)現(xiàn)圖片上傳功能 ?

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

首先在JSP上放一個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 {

SimpleDateFormat formatDate = new SimpleDateFormat("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ù)值

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對象

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);//計算新圖長寬

new_w=150;

new_h=110;//計算新圖長寬

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 Web的jsp制作圖片上傳和顯示如何實(shí)現(xiàn)

用jspSmartUpload組件來實(shí)現(xiàn),用jsp+servlet在Servlet里實(shí)現(xiàn)的代碼:

PrintWriter out = response.getWriter();

int count = 0;

// 實(shí)例化上傳控件對象

SmartUpload su = new SmartUpload();

// 初始化操作

su.initialize(config, request, response);

// 設(shè)置上傳文件最大字節(jié)數(shù)

su.setTotalMaxFileSize(100000);

//

try {

//禁止上傳指定擴(kuò)展名的文件

su.setDeniedFilesList("ext,bat,jsp");

} catch (SQLException e1) {

e1.printStackTrace();

}

try {

// 上傳文件到服務(wù)器

su.upload();

File fileup = new File(request.getRealPath("upload"));

if(!fileup.exists()){

// 創(chuàng)建目錄

fileup.mkdir();

}

// 處理多個文件的上傳

for(int i = 0;i su.getFiles().getCount();i++){

com.jspsmart.upload.File file = su.getFiles().getFile(i);

if(!file.isMissing()){ // 如果文件有效

// 保存文件到指定上傳目錄

file.saveAs("/upload/new."+file.getFileExt(), su.SAVE_VIRTUAL);

count = su.save("/upload");

}

}

} catch (SmartUploadException e) {

e.printStackTrace();

}

out.println(count +"file(s) uploaded");

如果你對這個上傳組件不了解,最好是先去查查用法。。。

java 求jsp上傳圖片到服務(wù)器代碼

提交頁面表單

form action="up.jsp" enctype="multipart/form-data" method="post"

input type="file" name="file"

input type="submit" value="確定"

/form

上傳頁面up.jsp

%@page import="java.io.FileWriter"%

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

import="java.io.*"

pageEncoding="UTF-8"%

%

/**

協(xié)議頭四行內(nèi)容

45 -----------------------------7de231211204c4

80 Content-Disposition: form-data; name="file"; filename="xx.txt"

26 Content-Type: text/plain

2

標(biāo)記文件結(jié)尾

-----------------------------7de231211204c4--

**/

ServletInputStream sin = request.getInputStream();

byte[] buffer = new byte[1024 * 8];

int length = 0, row = 0;

String mark = "";

String filename = "";

while ((length = sin.readLine(buffer, 0, buffer.length)) 0) {

out.println(length + " " + new String(buffer, 0, length, "UTF-8") + "br");

String s = new String(buffer, 0, length, "UTF-8");

if (row == 0)

mark = s.trim();

else if (s.indexOf("filename=") 0) {

int end = s.lastIndexOf("\"");

int start = s.substring(0, end).lastIndexOf("\"");

filename = s.substring(start + 1, end);

} else if ("".equals(s.trim()))

break;

row ++;

}

out.println("filename: " + filename + "br");

filename = request.getRealPath("/") + "../" + filename;

FileOutputStream fout = new FileOutputStream(filename);

while ((length = sin.readLine(buffer, 0, buffer.length)) 0) {

String s = new String(buffer, 0, length);

if (s.startsWith(mark))

break;

fout.write(buffer, 0, length);

}

fout.flush();

fout.close();

File f = new File(filename);

out.println(f.exists());

out.println(f.getAbsolutePath());

%

網(wǎng)頁名稱:java上傳圖片前端代碼 前端怎么實(shí)現(xiàn)上傳圖片
鏈接地址:http://muchs.cn/article48/hphshp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化網(wǎng)站排名、定制開發(fā)、小程序開發(fā)、移動網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計

廣告

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

成都定制網(wǎng)站網(wǎng)頁設(shè)計