圖片如何上傳java代碼 java圖片文件上傳
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)系我。
求JAVA上傳圖片代碼
public String imagesUpload(){
log.debug("images upload");
if(files == null){
saveMessage("沒(méi)有上傳任何文件!");
return ERROR;
}
// 查看上傳臨時(shí)目錄是否存在
String sep = File.separator;
String condPath = sep + "upload" + sep +"tmp" +sep;
String uploadDir = ServletActionContext.getServletContext().getRealPath(condPath) + sep;
File dirPath = new File(uploadDir);
if (!dirPath.exists())
dirPath.mkdirs();
String extension, fileName;
int count = 0;
StringBuilder picNameSB = new StringBuilder("");
ListString picNamesSet = new ArrayListString();
try{
for(File tempFile : files){
if(count0)
picNameSB.append("##");
extension = UserUtil.getFileExtension(filesFileName[count]);
fileName = generatePictureName(uploadDir, doType + count, extension);
File newFile = new File(fileName);
UserUtil.copyFileContent(tempFile,newFile);
picNamesSet.add(newFile.getName());
picNameSB.append(newFile.getName());
count++ ;
}
getSession().setAttribute("picNamesSet",picNamesSet);
picName = picNameSB.toString();
}catch(IOException e){
e.printStackTrace();
return ERROR;
}
int x= 1;
return SUCCESS;
}
private String generatePictureName(final String dir, final String suffix, final String fileExtension){
StringBuffer name = new StringBuffer(dir);
String tmpFileName = String.valueOf(System.currentTimeMillis());
if(suffix != null)
tmpFileName += suffix;
tmpFileName += "." + fileExtension;
name.append(tmpFileName);
return name.toString();
}
請(qǐng)問(wèn)用Java 如何實(shí)現(xiàn)圖片上傳功能 ?
我有一段上傳圖片的代碼,并且可以根據(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 {
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)保證在根目錄中有此目錄的存在 如果沒(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實(shí)現(xiàn)登陸代碼 用java實(shí)現(xiàn)登錄程序
欄 目:Java編程
下一篇:沒(méi)有了
本文標(biāo)題:圖片如何上傳java代碼 java圖片文件上傳
本文地址:http://www.jygsgssxh.com/a1/Javabiancheng/17383.html
您可能感興趣的文章
- 04-11java輪播圖片代碼 java實(shí)現(xiàn)輪播圖
- 04-10穿梭框后端JAVA代碼 穿梭框如何獲取右邊數(shù)據(jù)
- 04-10java改變字體代碼 java怎么改變字體
- 04-10java學(xué)習(xí)代碼庫(kù) java代碼教學(xué)
- 04-06整潔java代碼 java代碼例子講解
- 04-06Java寫(xiě)找朋友代碼 java示例代碼
- 04-06下載文件的java代碼 下載文件的java代碼是什么
- 04-05Java七夕代碼照片墻 java編程代碼圖片
- 04-03如何解讀java代碼 java代碼怎么讀
- 01-10SWT(JFace)體驗(yàn)之圖片的動(dòng)態(tài)漸變效果


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 7什么是 WSH(腳本宿主)的詳細(xì)解釋
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
- 10C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
本欄相關(guān)
- 04-12圖片如何上傳java代碼 java圖片文件上
- 04-12java實(shí)現(xiàn)登陸代碼 用java實(shí)現(xiàn)登錄程序
- 04-12java中定時(shí)評(píng)價(jià)代碼 java中定時(shí)評(píng)價(jià)代
- 04-12Java代碼的更新與刪除 java代碼的更新
- 04-12煙花特效java代碼 煙花特效cmd代碼制作
- 04-11背包問(wèn)題java代碼 java解決背包問(wèn)題
- 04-11java調(diào)用不同模塊代碼 java不同包怎樣
- 04-11java代碼建文件夾 java代碼創(chuàng)建文件
- 04-11java組件容器布局代碼 java設(shè)置組件位
- 04-11java自增長(zhǎng)代碼 java自增變量
隨機(jī)閱讀
- 01-10關(guān)于C語(yǔ)言程序的內(nèi)存分配的入門(mén)知識(shí)
- 08-05dedecms織夢(mèng)修復(fù)mysql數(shù)據(jù)庫(kù)表的方法
- 01-10SpringBoot Session共享實(shí)現(xiàn)圖解
- 01-10C#在WinForm中使用WebKit傳遞js對(duì)象實(shí)現(xiàn)與
- 01-10JQuery中的常用事件、對(duì)象屬性與使用
- 01-10WinForm中comboBox控件數(shù)據(jù)綁定實(shí)現(xiàn)方法
- 01-10C++中strtok()函數(shù)的用法介紹
- 08-05織夢(mèng)DeDecms無(wú)法自動(dòng)提取縮略圖的兩種
- 08-05dedecms的首頁(yè)、內(nèi)容頁(yè)、列表頁(yè)中 動(dòng)態(tài)
- 01-10使用批處理命令設(shè)置windows系統(tǒng)的ip地


