圖片如何上傳java代碼 java圖片文件上傳
java實現(xiàn)圖片上傳至服務器并顯示,如何做?希望要具體的代碼實現(xiàn)
很簡單。
可以手寫IO讀寫(有點麻煩)。
怕麻煩的話使用FileUpload組件 在servlet里doPost嵌入一下代碼
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html;charset=gb2312");
PrintWriter out=response.getWriter();
//設置保存上傳文件的目錄
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);
//采用默認的臨時文件存儲位置
//fu.setRepositoryPath(...);
//設置上傳的普通字段的名稱和文件字段的文件名所采用的字符集編碼
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" 屬性, 提交的時候要向服務器說明一下 此頁面包含文件。
如果 還是麻煩,干脆使用Struts 的上傳組件 他對FileUpload又做了封裝,使用起來更傻瓜化,很容易掌握。
-----------------------------
以上回答,如有不明白可以聯(lián)系我。
求JAVA上傳圖片代碼
public String imagesUpload(){
log.debug("images upload");
if(files == null){
saveMessage("沒有上傳任何文件!");
return ERROR;
}
// 查看上傳臨時目錄是否存在
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();
}
請問用Java 如何實現(xiàn)圖片上傳功能 ?
我有一段上傳圖片的代碼,并且可以根據(jù)實際,按月或按天等,生成存放圖片的文件夾
首先在JSP上放一個FILE的標簽這些我都不說了,你也一定明白,我直接把處理過程給你發(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+"/"); //應保證在根目錄中有此目錄的存在 如果沒有,下面則上創(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ù)庫的代友刪除了,這里就應該是判斷,你的圖片是不是已經(jī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()轉換大小寫
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); //構造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實現(xiàn)登陸代碼 用java實現(xiàn)登錄程序
欄 目:Java編程
下一篇:沒有了
本文地址:http://mengdiqiu.com.cn/a1/Javabiancheng/17383.html
您可能感興趣的文章
- 04-11java輪播圖片代碼 java實現(xiàn)輪播圖
- 04-10穿梭框后端JAVA代碼 穿梭框如何獲取右邊數(shù)據(jù)
- 04-10java改變字體代碼 java怎么改變字體
- 04-10java學習代碼庫 java代碼教學
- 04-06整潔java代碼 java代碼例子講解
- 04-06Java寫找朋友代碼 java示例代碼
- 04-06下載文件的java代碼 下載文件的java代碼是什么
- 04-05Java七夕代碼照片墻 java編程代碼圖片
- 04-03如何解讀java代碼 java代碼怎么讀
- 01-10SWT(JFace)體驗之圖片的動態(tài)漸變效果


閱讀排行
本欄相關
隨機閱讀
- 01-10關于C語言程序的內(nèi)存分配的入門知識
- 08-05dedecms織夢修復mysql數(shù)據(jù)庫表的方法
- 01-10SpringBoot Session共享實現(xiàn)圖解
- 01-10C#在WinForm中使用WebKit傳遞js對象實現(xiàn)與
- 01-10JQuery中的常用事件、對象屬性與使用
- 01-10WinForm中comboBox控件數(shù)據(jù)綁定實現(xiàn)方法
- 01-10C++中strtok()函數(shù)的用法介紹
- 08-05織夢DeDecms無法自動提取縮略圖的兩種
- 08-05dedecms的首頁、內(nèi)容頁、列表頁中 動態(tài)
- 01-10使用批處理命令設置windows系統(tǒng)的ip地