1. 程式人生 > >jsp頁面上傳圖片檔案到伺服器頁面無重新整理的技巧

jsp頁面上傳圖片檔案到伺服器頁面無重新整理的技巧

        最近做SSH專案碰到一個問題,我在頁面上想上傳一個圖片檔案到伺服器,但是在上傳前希望能在頁面上看到圖片的預覽。查了一下資料,發現有幾種方式可以完成這個功能。一種是通過javascript來實現這個預覽的功能,但是這種方法對瀏覽器有限制,有的瀏覽器用此方法無效。一種是通過ajax實現,還有一種就是通過無重新整理頁面上傳檔案到伺服器,通過顯示伺服器上的臨時圖片檔案也可以實現預覽的效果。

        下面講的就是最後一種方式。先看頁面檔案test.html原始碼:

<!DOCTYPE html>
<html>
  <head>
    <title>test.html</title>
	
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=GB18030">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

<script type="text/javascript">
function callback(msg)   
{   
    document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;   
    document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";   
}   
</script>
  </head>
  
  <body>
    <form action="/ECSystem/imgupload" id="form1" name="form1" encType="multipart/form-data"  method="post" target="hidden_frame">
      
    <input type="file" id="file" name="file" style="width:450" accept=".jpg, .gif">   
    <INPUT type="submit" value="上傳檔案"><span id="msg"></span>   
    <br>   
    <font color="red">支援JPG,JPEG,GIF,BMP,SWF,RMVB,RM,AVI檔案的上傳</font>               
    <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
  
  </body>
</html>
        上面的原始碼中,要上傳圖片檔案form的屬性裡必須有encType="multipart/form-data"  method="post"z,想要頁面不重新整理,“target="hidden_frame"這個是必要的設定,表示頁面的action請求重新整理到iframe裡,不必重新整理整個頁面。

        struts.xml檔案為設定為:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">  
        <action name="imgupload" class="com.struts.action.ImageUploadAction">
        </action>
    </package>
</struts>


        Action的程式碼實現ImageUploadAction.java內容:

package com.struts.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

import org.apache.struts2.ServletActionContext;



public class ImageUploadAction {
	private String fileFileName;
	private File file;
	private static final int BUFFER_SIZE = 64 * 1024 ; //緩衝器大小
	private String imageFileName;
	
	public void setFile(File file) {   
        this.file = file;   
    }
	
	public void setFileFileName(String fileFileName) {   
        this.fileFileName = fileFileName;   
    }
	
	public int getFileSizes(File f) throws Exception {//取得檔案大小
	       int s = 0;
	       if (f.exists()) {
	           FileInputStream fis = null;
	           fis = new FileInputStream(f);
	           s= fis.available();
	           if (fis != null)
	        	   fis.close();
	       }
	       return s;
	}
	
	private void copy(File src, File dst) throws Exception {
		if (!src.exists())
			return;
		PrintWriter document_out = ServletActionContext.getResponse().getWriter();
		Boolean result = true;
		int filesize = getFileSizes(src);
		try {
			InputStream in = null ;
			OutputStream out = null ;
			try { 
				in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
				byte [] buffer = new byte [BUFFER_SIZE];
				while (in.read(buffer, 0, filesize) > 0 ) {
					out.write(buffer, 0, filesize);
				}
			} finally {
				if ( null != in) {
					in.close();
				} 
				if ( null != out) {
					out.close();
				} 
			} 
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		} 
		if (result == true) {
			document_out.print("<script>parent.callback('upload file success');</script>");
		}
		else {
			document_out.print("<script>parent.callback('upload file fail');</script>");
		}
	} 
	
	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf( "." );
		return fileName.substring(pos);
	} 

	
	public String execute() throws Exception {
		
		imageFileName = new Date().getTime() + getExtention(this.fileFileName);
		File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/") + imageFileName);
		copy(file, imageFile);
		
		return "success";
	}

}

這樣就ok了

相關推薦

jsp頁面圖片檔案伺服器頁面重新整理技巧

        最近做SSH專案碰到一個問題,我在頁面上想上傳一個圖片檔案到伺服器,但是在上傳前希望能在頁面上看到圖片的預覽。查了一下資料,發現有幾種方式可以完成這個功能。一種是通過javascript來實現這個預覽的

基於VUE選擇圖片並在頁面顯示(圖片可刪除)

.ajax sta http data .cn 數據 file prim 生成 demo例子: 依賴文件 : http://files.cnblogs.com/files/zhengweijie/jquery.form.rar HTML文本內容:

HTML頁面圖片直接預覽

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上傳圖片</title> </head> <b

vue html jq 實現圖片顯示在頁面預覽

1、html程式碼 <img src="" alt="" id="myimg"> <input type="file" name="fileToUpload" id="fileToU

微信小程式 —— 檔案伺服器(例:圖片伺服器

上傳圖片到伺服器: 1.先在前端寫一個選擇圖片的區域來觸發wx.chooseImage介面並用wx.setStorage介面把圖片路徑存起來。 -wxml <view class="

圖片(檔案)在本地沒問題,伺服器上報錯413(Request Entity Too Large)

上傳這個問題困了我幾個小時才找到原因。 原因:伺服器使用了nginx,nginx預設的上傳檔案大小為1M,所以如果想上傳更大的檔案,就需要修改nginx的配置檔案。 操作:在nginx的配置檔案中的server下的server_name下,新增 client

H5 移動端圖片 和 視訊 頁面顯示縮圖

這是我第一次寫部落格,想要分享一下程式設計經驗,因為我也算是一個菜鳥而已,在程式設計過程中,很多問題 都是通過百度,通過CSDN裡面的各位大神分享的經驗,才得以解決的,所以我也是本著造福他人,也完善自己的意願,開始寫寫部落格,分享一下程式設計中遇到的問題及解決方法。好,廢話不

html頁面圖片並進行展示

html頁面: 本功能實現圖片上傳並顯示,點選“檢視”按鈕也顯示圖片 <div class="form-group"><label class="col-md-2 control-label">縮圖</label><div clas

七牛雲單頁面圖片的功能

<?php date_default_timezone_set("Asia/Shanghai"); //設定時區 //插入七牛雲的類庫 require_once('../../library/qiniu/rs.php'); require_once('../../l

jsp+servlet實現圖片伺服器並返回下載該圖片的二維碼

下面這個是利用java實現將一張圖片上傳到伺服器上並且返回下載該圖片的二維碼 其中用到的生成二維碼的外掛是zxing 廢話不多說直接上程式碼 package com.gzar.servlet; import java.io.File; import java.io.I

springboot(7)——圖片/檔案到七牛雲端儲存

一、七牛雲快速入門 快速入門 1、註冊賬號 2、建立儲存空間, 命名xyz對應下面springboot 應用配置bucket 3、建立成功後進入該空間,獲取該空間的測試域名,對應下面springboot 應用配置中的path 4、點選“個人面板—金鑰管理

FormData物件提交表單及圖片/檔案

1.建立一個FormData空物件,然後使用append方法新增key/value var formdata = new FormData(); formdata.append('name','fdipzone'); formdata.append('gender','male');

vue-quill-editor-upload : 實現vue-quill-editor圖片伺服器

vue-quill-editor-upload git: https://github.com/NextBoy/vu... A plug-in for uploading images to your server when you use vue-quill-editor. 富文字編輯器vue-qui

Swoft 踩坑筆記八 - 圖片/檔案

emmmmmmmmmmmm,官方文件連線收檔案的程式碼都沒寫。。 試了下 $file = $request->file('file'); 這是接收到的圖片 然後咋辦?然後。。其實。。大佬給的程式碼是這樣的: $files = $request->getUplo

wangedit圖片伺服器

後臺 @ApiOperation(notes = "返回一個檔名,需要呼叫 /home/download方法才可以獲取到檔案", httpMethod = "POST", value = "檔案/圖片上傳") @RequestMapping("/uploaderPic2") @Respon

vue 整合ueditor(百度富文字編輯器)以及使用後端Java圖片伺服器,特別注意的大坑

    1.import 引入ueditor時,在封裝元件中引入,不要在mian.js內引入,在main.js內引入會造成 1.Uncaught SyntaxError: Unexpected token : 這種錯誤,屬於是跨域問題,目前不清楚是什麼原因和原理,

圖片伺服器,並且重新命名圖片-更改(小白共勉)

實現使用者註冊功能,使用者上傳頭像放在imgs的目錄下,所涉及檔案分別是register.html(註冊),conn.php(連線資料庫),img.php(上傳圖片與更改圖片名稱,改成了是一個函式,返回 圖片儲存位置+圖片名稱),register.php(註冊功能) register.html介

圖片伺服器,並且重新命名圖片(小白共勉)

根據教程上更改的,含冗餘,會再改,小白共勉 檔案所含內容如下(不知道為啥編輯器不能給字型改變顏色了,鬱悶): upload資料夾為存放圖片資料夾,注意upload、imgnewname.php、index.html、upload_file.php為同一級、 為了可以多次呼叫更改名稱

微信小程式圖片檔案 小程式+Java

小程式程式碼: chooseImage(){ wx.chooseImage({ success: function (res) { var tempFilePaths = res.tempFilePaths wx.up

html input type="file" 只允許圖片檔案

<from action="" enctype="multipart/form-data" method="post"> <a> <span>修改頭像</span> <input t