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

jspjava上傳圖片

發布時間: 2022-05-23 15:37:21

『壹』 java怎麼上傳圖片然後顯示在JSP頁面中

java上圖片和上傳文件的方式是一樣的... 都是將文件上傳到指定目錄後,地址放入資料庫中.
這種方式, 只需要學習下 apache中的common下的upload包 操作即可.
如果是struts, 帶有這個jar包的

『貳』 java 求jsp上傳圖片到伺服器代碼

提交頁面表單
<form action="up.jsp" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="確定">
</form>
上傳頁面up.jsp
<%@page import="java.io.FileWriter"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.io.*"
pageEncoding="UTF-8"%>
<%
/**
協議頭四行內容
45 -----------------------------7de231211204c4
80 Content-Disposition: form-data; name="file"; filename="xx.txt"
26 Content-Type: text/plain
2
標記文件結尾
-----------------------------7de231211204c4--
**/
ServletInputStream sin = request.getInputStream();
byte[] buffer = new byte[1024 * 8];
int length = 0, row = 0;
String mark = "";
String filename = "";
while ((length = sin.readLine(buffer, 0, buffer.length)) > 0) {
out.println(length + " " + new String(buffer, 0, length, "UTF-8") + "<br>");
String s = new String(buffer, 0, length, "UTF-8");
if (row == 0)
mark = s.trim();
else if (s.indexOf("filename=") > 0) {
int end = s.lastIndexOf("\"");
int start = s.substring(0, end).lastIndexOf("\"");
filename = s.substring(start + 1, end);
} else if ("".equals(s.trim()))
break;
row ++;
}

out.println("filename: " + filename + "<br>");
filename = request.getRealPath("/") + "../" + filename;
FileOutputStream fout = new FileOutputStream(filename);
while ((length = sin.readLine(buffer, 0, buffer.length)) > 0) {
String s = new String(buffer, 0, length);
if (s.startsWith(mark))
break;
fout.write(buffer, 0, length);
}
fout.flush();
fout.close();
File f = new File(filename);
out.println(f.exists());
out.println(f.getAbsolutePath());
%>

『叄』 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();
}

『肆』 請問jsp頁面如何上傳照片到伺服器呢,

這個是我以前用的一個用jsp上傳的,servlet是一樣的,你可以自己修改下。
普通參數也是可以接受的

在jsp頁面中你需要導入jsmart的中文jar包,如果你需要的話可以密我,我郵箱發給你
上傳頁面upload.html
<html>

<head>

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>

<body>

<form action="uploadfile.jsp" method="post" enctype="multipart/form-data">

<table width="380" border="0" align="center" cellpadding="0" cellspacing="0" style="font-size:12px;">
<tr>
<td height="40" align="right">節目名稱:</td>
<td><input type="text" style="WIDTH: 210px" id="mcdb_content" name="mcdb_content" /></td>
</tr>
<td height="40" align="right">節目鏈接地址:</td>
<td><input type="text" style="WIDTH: 210px" id="linkUrl" name="linkUrl" /></td>
</tr>
<tr>
<td height="40" align="right" valign="middle">
上傳焦點圖片:</td>
<td><input type="file" name="upfile" id="file"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="提交"></td>
</tr>
</table>
</form>

</body>

</html>

處理上傳文件的頁面uploadfile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="com.jspsmart.upload.*;" %>
<%
SmartUpload mySmartUpload =new SmartUpload();

//上傳文件的限制大小
long file_size_max=4000000;

String fileName2="",ext="",testvar="";

//應保證在根目錄中有此目錄的存在(也就是說需要自己建立相應的文件夾
String url="/upload/";

//初始化
mySmartUpload.initialize(pageContext);

//只允許上載此類文件
try {

mySmartUpload.setAllowedFilesList("bmp,jpg,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw");//此處的文件格式可以根據需要自己修改

//上載文件
mySmartUpload.upload();

} catch (Exception e){

//上傳類型出現異常
%>

<SCRIPT language=javascript>

alert("只允許上傳圖片");

window.location='upload.html';

</script>

<%

}

try{
//得到上傳的文件
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);

//如果文件獲得為空
if (myFile.isMissing()){%>

<SCRIPT language=javascript>

alert("請先選擇要上傳的文件");

window.location='upload.html';

</script>

<%}
//得到了上傳的文件
else{

//String myFileName=myFile.getFileName(); //取得上載的文件的文件名

ext= myFile.getFileExt(); //取得後綴名

int file_size=myFile.getSize(); //取得文件的大小

String saveurl="";

//如果文件沒有超過限制上傳的大小
if(file_size<file_size_max){

//更改文件名,取得當前上傳時間的毫秒數值
Calendar calendar = Calendar.getInstance();
String filename = String.valueOf(calendar.getTimeInMillis());
saveurl=application.getRealPath("/")+url;

String filenamea="";

//保存路徑
saveurl+=filename+"."+ext;
filenamea+=filename+"."+ext;

//接受普通參數
Request req = mySmartUpload.getRequest();
String bt=(String)req.getParameter("mcdb_content");
String linkurl = (String)req.getParameter("linkUrl");

myFile.saveAs(saveurl,SmartUpload.SAVE_PHYSICAL);

out.print(filenamea);

}

}

}catch (Exception e){

out.print(e.toString());

}

%>

『伍』 用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 web jsp怎麼插圖片

JSP中插入的圖片就是一個html的img標簽,如
<img src="images/hi.png"/>
1. 上傳圖片到伺服器的文件系統中
2. 把圖片的地址保存到資料庫
3. 讀取圖片的地址,設置到<img src=".."/>的src屬性中

『柒』 java,jsp,javabean:怎麼實現上傳圖像

呵呵 我剛做了個非同步上傳圖片的功能 代碼原封不動的給你發過來 ;
upload.jsp------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>文件上傳</title>
<link rel="stylesheet" type="text/css"
href="<%=basePath%>/style/css/style.css">
<Script TYPE="text/javascript" src="<%=basePath%>/common/js/jquery.min.js"></Script>
<script type="text/javascript"
src="<%=basePath%>/common/js/ajaxfileupload.js"></script>
<script type="text/javascript">
var bathPath= "/" + window.document.location.pathname.split("/")[1]+"/";
var divId=getParam("divId");
var componentName=getParam("componentName");
var photoSrc=getParam("photoSrc");
jQuery(document).ready(function(){
if(photoSrc!=null&&photoSrc!=""){
jQuery("<div><image src=\"" + photoSrc + "\" height='80px' /></div>").appendTo("#img");
}
}
)
function getParam(param){
var url=window.location.href;
var paramUrl = url.substr(url.indexOf("?")+1,url.length).replace("#","");
var arrParam = paramUrl.split("&");
for(var i = 0; i<arrParam.length; i++){
if(arrParam[i].split("=")[0] == param){
return arrParam[i].split("=")[1];
}
}
}

function upload(){
$.ajaxFileUpload({
url:'uploadphoto.action', //需要鏈接到伺服器地址
secureuri:false,
fileElementId:'fileid', //文件選擇框的id屬性
dataType: 'text', //伺服器返回的格式,可以是json
success: function (result, status) //相當於java中try語句塊的用法
{ //data是從伺服器返回來的值
if(result=="false"){
alert("上傳失敗");
}
else{
alert("上傳成功");
$("#img").empty();
var src=bathPath+result;
$("<div><image src=\"" + src + "\" height='80px' /></div>").appendTo("#img");
}
jQuery("#"+divId,window.parent.document).empty();
jQuery("#"+divId,window.parent.document).append("<input type='hidden' id='dddddd' value=" + result +" name=" + componentName +" ");
}
}

);
}

var jpgFile = true;
function getFileName(obj) {
var posStart = obj.value.lastIndexOf("\\") * 1;
var posEnd = obj.value.lastIndexOf(".") * 1;
return obj.value.substring(posStart + 1, posEnd);
}

function getFileExt(obj) {
var posEnd = obj.value.lastIndexOf(".") * 1;
return obj.value.substring(posEnd + 1);
}
function getFFFileName() {
var allName = document.getElementById('fileid').value;
var posStart = "";
var posEnd = allName.lastIndexOf(".") * 1;
return allName.substring(posStart, posEnd);
}

function getFFFileExt() {
var allName = document.getElementById('fileid').value;
var posEnd = allName.lastIndexOf(".") * 1;
return allName.substring(posEnd + 1);
}
function ifJpgFile(obj) {
var filename;
var fileext;
if (window.navigator.userAgent.indexOf("MSIE") >= 1) {
filename = getFileName(obj);
fileext = getFileExt(obj);
} else if (window.navigator.userAgent.indexOf("Firefox") >= 1) {
filename = getFFFileName();
fileext = getFFFileExt();
}

var fileType = document.getElementById('fileid').value;
var lastIndexOfDot = fileType.lastIndexOf('.');
fileType = fileType.substr(lastIndexOfDot).toLowerCase();
if (fileType != '.jpg'&& fileType != '.jpeg'&& fileType != '.gif'&& fileType != '.bmp'&&fileType != '.png'&&fileType != '.tif') {
jpgFile = false;
} else {
jpgFile = true;
}
}

function chk() {
if (document.getElementById('fileid').value == '') {
alert('請選擇要上傳的文件!');
return false;
} else if (jpgFile) {
upload();
} else {
alert('請上傳圖片文件!');
}
}
</script>
</head>
<body>
<div id="img"></div>
文件:
<input id="fileid" size="10" type="file" name="zip" onchange="ifJpgFile(this)">
<br>
<input type="button" value="上傳" onclick="chk()" />
</body>
</html>
ajaxfileupload.js--------------------------------------------
// JavaScript Document
jQuery.extend({

createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;

if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';

document.body.appendChild(io);

return io;
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},

ajaxFileUpload: function(s) {
// TODO introce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;

if( s.global && ! jQuery.active++ )
{
// Watch for a new set of requests
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {};
if( s.global )
{
jQuery.event.trigger("ajaxSend", [xml, s]);
}

var uploadCallback = function(isTimeout)
{
// Wait for a response to come back
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
if( s.success )
{
// ifa local callback was specified, fire it and pass it the data
s.success( data, status );
};
if( s.global )
{
// Fire the global callback
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
};
} else
{
jQuery.handleError(s, xml, status);
}

} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
};
if( s.global )
{
// The request was completed
jQuery.event.trigger( "ajaxComplete", [xml, s] );
};

// Handle the global AJAX counter
if(s.global && ! --jQuery.active)
{
jQuery.event.trigger("ajaxStop");
};
if(s.complete)
{
s.complete(xml, status);
} ;

jQuery(io).unbind();

setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();

} catch(e)
{
jQuery.handleError(s, xml, null, e);
}

}, 100);

xml = null;

};
}
// Timeout checker
if( s.timeout > 0 )
{
setTimeout(function(){

if( !requestDone )
{
// Check to see ifthe request is still happening
uploadCallback( "timeout" );
}

}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
jQuery(form).submit();

} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};

},

uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if( type == "script" )
{
jQuery.globalEval( data );
}

// Get the JavaScript object, ifJSON is used.
if( type == "json" )
{
eval( "data = " + data );
}

// evaluate scripts within html
if( type == "html" )
{
jQuery("<div>").html(data).evalScripts();
}

return data;
}
});

upload.action------------------------------------------
package com.tjopen.define.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.tjopen.base.util.Util;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
private File zip;
private String zipFileName;
private String realpath;
private String filePath;
public void uploadphoto(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 保存到項目的路徑下
String basePath = ServletActionContext.getServletContext().getRealPath("/");
SimpleDateFormat formater = new SimpleDateFormat("yyyy-M-dd");
String middlePath = "resources/photo/" + formater.format(new Date());
String tempMiddlePath = "";

// 生成時間戳文件夾路徑
String str = "";
for (int i = 1; i < 100000; i++) {
tempMiddlePath = middlePath + "_" + i + "/";
str = middlePath + "_" + (i - 1 < 1 ? 1 : i - 1) + "/";
File parentDir = new File(basePath + tempMiddlePath);

if (parentDir.exists()) {
continue;
} else {
parentDir = new File(basePath + str);
if (parentDir != null && parentDir.list() != null && parentDir.list().length < 200) {
middlePath = str;
} else {
middlePath = tempMiddlePath;
}
break;
}
}
// 保存文件名
String filename=zipFileName;
String savefilePath=basePath+middlePath+filename;
File savefile = new File(savefilePath);
String result=middlePath+filename;
if(zip!= null){
try {
FileUtils.File(zip, savefile);
} catch (IOException e) {
result="false";
}
}
else{
result="false";
}
try {
response.getWriter().print(result);
} catch (IOException e) {
e.printStackTrace();
}
}

public File getZip() {
return zip;
}

public void setZip(File zip) {
this.zip = zip;
}

public String getZipFileName() {
return zipFileName;
}

public void setZipFileName(String zipFileName) {
this.zipFileName = zipFileName;
}

public String getFilePath() {
return filePath;
}

public void setFilePath(String filePath) {
this.filePath = filePath;
}

}

『捌』 用jsp、java實現上傳圖片,保存到資料庫,從資料庫中提取,顯示到頁面 這四步 我想問第一步,怎麼上傳圖片

用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");

如果你對這個上傳組件不了解,最好是先去查查用法。。。

如果對您有幫助,請記得採納為滿意答案,謝謝!祝您生活愉快!

vaela

『玖』 java jsp 我現在是用jspsmartupload上傳圖片,現在已經可以把圖片保存到相應的路徑,,

<scripttype="text/javascript"charset="utf-8">

functionchange(e){
varsrc=e.target||window.event.srcElement;//獲取事件源,兼容chrome/IE
src.style.background='red';

alert(src.value);

//測試chrome瀏覽器、IE6,獲取的文件名帶有文件的path路徑
//下面把路徑截取為文件名
varfilename=src.value;
alert(filename.substring(filename.lastIndexOf('\')+1));


//獲取文件名的後綴名(文件格式)
alert(filename.substring(filename.lastIndexOf('.')+1));
}
</script>
</head>
<body>
選擇文件:
<br>
<inputtype='file'onchange="change(event);">

</body>

熱點內容
qq刷紅包腳本 發布:2024-05-03 16:16:54 瀏覽:769
c服務編譯耗時優化原理及實例 發布:2024-05-03 15:35:26 瀏覽:15
ue編程 發布:2024-05-03 15:34:40 瀏覽:610
經典的c語言程序 發布:2024-05-03 15:03:24 瀏覽:859
工程加密網 發布:2024-05-03 14:59:55 瀏覽:292
吃冰球解壓 發布:2024-05-03 14:59:10 瀏覽:895
編譯晶元發燙 發布:2024-05-03 14:59:05 瀏覽:549
優化演算法pdf 發布:2024-05-03 14:18:10 瀏覽:291
python演算法書 發布:2024-05-03 14:14:25 瀏覽:736
方舟怎麼加入伺服器閃退 發布:2024-05-03 14:05:27 瀏覽:491