本文目錄一覽:
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.設置字元編碼、
su.setCharset(“UTF-8”);
//5.設置的單個上傳最大限制
su.setMaxFileSize(5*1024*1024);
//6.總共上傳限制
su.setTotalMaxFileSize(20*1024*1024);
//7.上傳
su.upload();
//su.getFiles().getCount() 獲取上傳數
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怎樣上傳圖片(寫個例子謝謝);
我有一段上傳圖片的代碼,並且可以根據實際,按月或按天等,生成存放圖片的文件夾
首先在JSP上放一個FILE的標籤這些我都不說了,你也一定明白,我直接把處理過程給你發過去
我把其中存到資料庫中的內容刪除了,你改一下就能用
/**
*
* 上傳圖片
* @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+”/”); //應保證在根目錄中有此目錄的存在 如果沒有,下面則上創建新的文件夾
if(!root.isDirectory())
{
System.out.println(“創建新文件夾成功”+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{
//我上面說到,把操作資料庫的代友刪除了,這裡就應該是判斷,你的圖片是不是已經存在了,存在要怎麼處理,不存在要怎麼處了,就是你的事了 }
//更改文件名,取得當前上傳時間的毫秒數值
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);
//將圖片信息插入到資料庫中
// ——上傳完成,開始生成縮略圖—–
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 中圖片上傳問題
e,伺服器可以用ServerSocket,客戶端用Socket
然後就
Socket s=new Socket……………
OutputStream out=s.getOutputStream();
File f=圖片文件;
FileInputStream in=new FileInputStream(f);
byte data[]=byte[1024];
int length=0;
while((length=in.read(data,0,1024))!=-1) out.write(data,0,length);
out.close();
in.close();
伺服器端
ServerSocket s=new ServerSocket……………
//accept…..
InputStream in=s.getInputStream();
File f=圖片文件;
FileOutputStream out=new FileOutputStream(f);
byte data[]=byte[1024];
int length=0;
while((length=in.read(data,0,1024))!=-1) out.write(data,0,length);
out.close();
in.close();
然後伺服器接到請求時(這個是Servlet)
PrintWriter writer=resp.getWriter(); //resp–HttpServletResponse
….
writer.print(“img src=\”+圖片路徑+”\””);
That’s all.
用java怎麼上傳圖片到項目指定的文件夾
你的意思是拷貝嗎,還是上傳到伺服器什麼的
import java.io.*;
/**
* 複製文件夾或文件夾
*/
public class CopyDirectory {
// 源文件夾
static String url1 = “f:/photos”;
// 目標文件夾
static String url2 = “d:/tempPhotos”;
public static void main(String args[]) throws IOException {
// 創建目標文件夾
(new File(url2)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(url1)).listFiles();
for (int i = 0; i file.length; i++) {
if (file[i].isFile()) {
// 複製文件
copyFile(file[i],new File(url2+file[i].getName()));
}
if (file[i].isDirectory()) {
// 複製目錄
String sourceDir=url1+File.separator+file[i].getName();
String targetDir=url2+File.separator+file[i].getName();
copyDirectiory(sourceDir, targetDir);
}
}
}
// 複製文件
public static void copyFile(File sourceFile,File targetFile)
throws IOException{
// 新建文件輸入流並對它進行緩衝
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff=new BufferedInputStream(input);
// 新建文件輸出流並對它進行緩衝
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff=new BufferedOutputStream(output);
// 緩衝數組
byte[] b = new byte[1024 * 5];
int len;
while ((len =inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此緩衝的輸出流
outBuff.flush();
//關閉流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 複製文件夾
public static void copyDirectiory(String sourceDir, String targetDir)
throws IOException {
// 新建目標目錄
(new File(targetDir)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile=file[i];
// 目標文件
File targetFile=new
File(new File(targetDir).getAbsolutePath()
+File.separator+file[i].getName());
copyFile(sourceFile,targetFile);
}
if (file[i].isDirectory()) {
// 準備複製的源文件夾
String dir1=sourceDir + “/” + file[i].getName();
// 準備複製的目標文件夾
String dir2=targetDir + “/”+ file[i].getName();
copyDirectiory(dir1, dir2);
}
}
}
}
java 中如何向伺服器上傳圖片
我們使用一些已有的組件幫助我們實現這種上傳功能。
常用的上傳組件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload為例講解
1、在jsp端
form id=”form1″ name=”form1″ method=”post” action=”servlet/fileServlet” enctype=”multipart/form-data”
要注意enctype=”multipart/form-data”
然後只需要放置一個file控制項,並執行submit操作即可
input name=”file” type=”file” size=”20″
input type=”submit” name=”submit” value=”提交”
2、web端
核心代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(“UTF-8”);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println(“表單參數名:” + item.getFieldName() + “,表單參數值:” + 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());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath(“/”) + savePath, tempFile.getName());
item.write(file);
request.setAttribute(“upload.message”, “上傳文件成功!”);
}else{
request.setAttribute(“upload.message”, “沒有選擇上傳文件!”);
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute(“upload.message”, “上傳文件失敗!”);
}
request.getRequestDispatcher(“/uploadResult.jsp”).forward(request, response);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239687.html