當前位置:首頁 » 文件管理 » java圖片上傳預覽

java圖片上傳預覽

發布時間: 2024-06-12 19:49:00

㈠ 如何在spring mvc中上傳圖片並顯示出來

(1)在spring mvc的配置文件中配置:

<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<propertyname="uploadTempDir"value="/tmp"/><!--臨時目錄-->
<propertyname="maxUploadSize"value="10485760"/><!--10M-->
</bean>

(2)文件上傳表單和結果展示頁fileupload.jsp:

<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglibprefix="mvc"uri="http://www.springframework.org/tags/form"%>
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>SpringMVC文件上傳</title>
</head>
<body>
<h2>圖片文件上傳</h2>
<mvc:formmodelAttribute="user"action="upload.html"
enctype="multipart/form-data">
<table>
<tr>
<td>用戶名:</td>
<td><mvc:inputpath="userName"/></td>
</tr>
<tr>
<td>選擇頭像:</td>
<td><inputtype="file"name="file"/></td>
</tr>
<tr>
<tdcolspan="2"><inputtype="submit"value="Submit"/></td>
</tr>
</table>
</mvc:form>
<br><br>
<c:iftest="${u!=null}">
<h2>上傳結果</h2>
<table>
<c:iftest="${u.userName!=null}">
<tr>
<td>用戶名:</td>
<td>${u.userName}</td>
</tr>
</c:if>
<c:iftest="${u.logoSrc!=null}">
<tr>
<td>頭像:</td>
<td><imgsrc="${u.logoSrc}"width="100px"height="100px"></td>
</tr>
</c:if>

</table>

</c:if>

</body>
</html>

(3)後台處理UploadController.java:

packagecn.zifangsky.controller;

importjava.io.File;
importjava.io.IOException;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.commons.io.FileUtils;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.servlet.ModelAndView;

importcn.zifangsky.model.User;
importcn.zifangsky.utils.StringUtile;

@Controller
publicclassUploadController{

@RequestMapping(value="/form")
publicModelAndViewform(){
ModelAndViewmodelAndView=newModelAndView("fileupload","user",newUser());

returnmodelAndView;
}

@RequestMapping(value="/upload",method=RequestMethod.POST)
publicModelAndViewupload(Useruser,@RequestParam("file")MultipartFiletmpFile,HttpServletRequestrequest){
ModelAndViewmodelAndView=newModelAndView("fileupload");

if(tmpFile!=null){
//獲取物理路徑
StringtargetDirectory=request.getSession().getServletContext().getRealPath("/uploads");
StringtmpFileName=tmpFile.getOriginalFilename();//上傳的文件名
intdot=tmpFileName.lastIndexOf('.');
Stringext="";//文件後綴名
if((dot>-1)&&(dot<(tmpFileName.length()-1))){
ext=tmpFileName.substring(dot+1);
}
//其他文件格式不處理
if("png".equalsIgnoreCase(ext)||"jpg".equalsIgnoreCase(ext)||"gif".equalsIgnoreCase(ext)){
//重命名上傳的文件名
StringtargetFileName=StringUtile.renameFileName(tmpFileName);
//保存的新文件
Filetarget=newFile(targetDirectory,targetFileName);

try{
//保存文件
FileUtils.InputStreamToFile(tmpFile.getInputStream(),target);
}catch(IOExceptione){
e.printStackTrace();
}

Useru=newUser();
u.setUserName(user.getUserName());
u.setLogoSrc(request.getContextPath()+"/uploads/"+targetFileName);

modelAndView.addObject("u",u);
}

returnmodelAndView;
}

returnmodelAndView;
}

}

在上面的upload方法中,為了接收上傳的文件,因此使用了一個MultipartFile類型的變數來接收上傳的臨時文件,同時為了給文件進行重命名,我調用了一個renameFileName方法,這個方法的具體內容如下:

/**
*文件重命名
*/
(StringfileName){
StringformatDate=newSimpleDateFormat("yyMMddHHmmss").format(newDate());//當前時間字元串
intrandom=newRandom().nextInt(10000);
Stringextension=fileName.substring(fileName.lastIndexOf("."));//文件後綴

returnformatDate+random+extension;
}

註:上面用到的model——User.java:

packagecn.zifangsky.model;

publicclassUser{
privateStringuserName;//用戶名
privateStringlogoSrc;//頭像地址

publicStringgetUserName(){
returnuserName;
}

publicvoidsetUserName(StringuserName){
this.userName=userName;
}

publicStringgetLogoSrc(){
returnlogoSrc;
}

publicvoidsetLogoSrc(StringlogoSrc){
this.logoSrc=logoSrc;
}

}

至此全部結束

效果如下:

(PS:純手打,望採納)

㈡ 用Java Web的jsp製作圖片上傳和顯示如何實現

用jspSmartUpload組件來實現,用jsp+servlet在Servlet里實現的代碼:

PrintWriter out = response.getWriter();
int count = 0;
// 實例化虧友上傳控制項對象
SmartUpload su = new SmartUpload();
// 初始化操作
su.initialize(config, request, response);

// 設置上傳文件最大位元組數
su.setTotalMaxFileSize(100000);

//
try {
//禁止上傳指定擴展和空喚名的文件
su.setDeniedFilesList("ext,bat,jsp");
} catch (SQLException e1) {
e1.printStackTrace();
}

try {
// 上傳文件到伺服器
su.upload();

File fileup = new File(request.getRealPath("upload"));
if(!fileup.exists()){
// 創建目錄
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上傳圖片 生成縮略圖,如果上傳的圖片尺寸比較小就壓縮處理

//將圖按比例縮小。
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分別表示目標長和寬
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
//這里想實現在targetW,targetH范圍內實現等比縮放。如果不需要等比縮放
//則將下面的if else語句注釋即可
if(sx>sy)
{
sx = sy;
targetW = (int)(sx * source.getWidth());
}else{
sy = sx;
targetH = (int)(sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { //handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}

public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)
throws Exception {
BufferedImage srcImage;
// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
String imgType = "JPEG";
if (fromFileStr.toLowerCase().endsWith(".png")) {
imgType = "PNG";
}
// System.out.println(ex);
File saveFile=new File(saveToFileStr);
File fromFile=new File(fromFileStr);
srcImage = ImageIO.read(fromFile);
if(width > 0 || hight > 0)
{
srcImage = resize(srcImage, width, hight);
}
ImageIO.write(srcImage, imgType, saveFile);

}

public static void main (String argv[]) {
try{
//參數1(from),參數2(to),參數3(寬),參數4(高)
saveImageAsJpg("C:\\Documents and Settings\\xugang\\桌面\\tmr-06.jpg",
"C:\\Documents and Settings\\xugang\\桌面\\2.jpg",
120,120);
} catch(Exception e){
e.printStackTrace();
}

}

㈣ 請問用Java 如何實現圖片上傳功能

自己寫程序來上傳位元組流文件很難的,用SmartUpload.jar包吧,專門用於JSP上傳下載的,唯一缺點就是中文支持不太好,不過你可以改一下原程序的字元集就行了。上網搜,沒有找我!我給你發

㈤ java實現圖片上傳至伺服器並顯示,如何做希望要具體的代碼實現

很簡單。
可以手寫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;
}
//根據路徑創建一個文件
File fUploadDir = new File(uploadDir);
if(!fUploadDir.exists()){
if(!fUploadDir.mkdir())//如果UP目錄不存在 創建一個 不能創建輸出...
{
out.println("無法創建存儲目錄!");
return;
}
}

if (!DiskFileUpload.isMultipartContent(request))
{
out.println("只能處理multipart/form-data類型的數據!");
return ;
}

DiskFileUpload fu = new DiskFileUpload();
//最多上傳200M數據
fu.setSizeMax(1024 * 1024 * 200);
//超過1M的欄位數據採用臨時文件緩存
fu.setSizeThreshold(1024 * 1024);
//採用默認的臨時文件存儲位置
//fu.setRepositoryPath(...);
//設置上傳的普通欄位的名稱和文件欄位的文件名所採用的字元集編碼
fu.setHeaderEncoding("gb2312");

//得到所有表單欄位對象的集合
List fileItems = null;
try
{
fileItems = fu.parseRequest(request);//解析request對象中上傳的文件

}
catch (FileUploadException e)
{
out.println("解析數據時出現如下問題:");
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("存儲文件時出現如下問題:");
e.printStackTrace(out);
return;
}
finally //總是立即刪除保存表單欄位內容的臨時文件
{
fi.delete();
}

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

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

-----------------------------
以上回答,如有不明白可以聯系我。

㈥ java實現圖片上傳至伺服器並顯示,如何做

給你段代碼,是用來在ie上顯示圖片的(servlet):

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
File file = new File(getServletContext().getRealPath("/")+"out"+"/"+id+".gif");
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));

System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));

OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);

byte[] b = new byte[1024];
int i = 0;

while((i = fis.read(b))!=-1)
{

output.write(b, 0, i);
}
output.write(b, 0, b.length);

output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}

}

這個程序的功能是根據傳入的文件名(id),來為瀏覽器返回圖片流,顯示在<img>標簽里
標簽的格式寫成如下:
<img src="http://localhost:8080/app/preview?id=111 "/><br/>
顯示的是111.gif這個圖片

你上面的問題:
1.我覺得你的第二個辦法是對的,我們也是這樣做的,需要的是把資料庫的記錄id號傳進servlet,然後讀取這條記錄中的路徑信息,生成流以後返回就是了

關於上傳文件的問題,我記得java中應該專門有個負責文件上傳的類,你調用就行了,上傳後存儲在指定的目錄里,以實體文件的形式存放
你可以參考這個:
http://blog.csdn.net/arielxp/archive/2004/09/28/119592.aspx

回復:
1.是的,在response中寫入流就行了
2.是發到servlet中的,我們一般都是寫成servlet,短小精悍,使用起來方便,struts應該也可以,只是我沒有試過,恩,你理解的很對

㈦ Java在jsp中 如何上傳圖片 在上傳時可以取到圖片大小並修改

用第三方工具去取 common-upload,具體取到圖片的方法參考代碼如下:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
upload.setHeaderEncoding("utf-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
System.out.println("fileName=" + fileItem.getFieldName());
//獲取文件流
InputStream in = fileItem.getInputStream();
ServletContext context = getServletConfig().getServletContext();
String path = context.getRealPath("image");
System.out.println(path);
OutputStream out = new FileOutputStream(new File(path + "\\" + fileItem.getName()));
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("寫入完畢");
}
} catch (FileUploadException e) {
e.printStackTrace();
}

㈧ 我用java寫了個上傳圖片的功能,上傳後為什麼只有重啟tomcat後,圖片才能顯示呢

不能把文件傳到項目的工作空間去了,應該傳到tomcat對應的項目下才行.
比如我的tomcat裝在c盤下的,那麼在路徑C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps下會有個和工作空間里項目一樣名稱的文件夾,得把文件傳到這里.

熱點內容
二維otsu演算法 發布:2024-10-22 21:06:23 瀏覽:634
福祿壽源碼 發布:2024-10-22 21:06:13 瀏覽:434
pythongoagent 發布:2024-10-22 20:42:05 瀏覽:78
matlabpid演算法 發布:2024-10-22 20:37:51 瀏覽:332
文件遍歷編程 發布:2024-10-22 20:37:47 瀏覽:622
nip伺服器地址在哪 發布:2024-10-22 20:17:48 瀏覽:621
戶戶通衛星鍋出廠設置密碼是什麼 發布:2024-10-22 20:11:32 瀏覽:759
怎麼將伺服器的文件導出來 發布:2024-10-22 20:09:13 瀏覽:556
直播秀場源碼 發布:2024-10-22 20:08:22 瀏覽:751
php遠程資料庫 發布:2024-10-22 20:03:05 瀏覽:730