上传图片到服务器如何写代码?

上传图片到服务器如何写代码?,第1张

<%

'/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\'

'\建站铺 jzpu.com 2007 7.18 /'

'/ CODE version 4.8 express \'

'\请保留信息,以便确认版本区别 /'

'/__________________________________\'

Dim oUpFileStream

Class UpFile_Class

Dim Form, File, Version, Err

Private Sub Class_Initialize

Err = -1

End Sub

Private Sub Class_Terminate

If Err <0 Then

Form.RemoveAll

Set Form = Nothing

File.RemoveAll

Set File = Nothing

oUpFileStream.Close

Set oUpFileStream = Nothing

End If

End Sub

Public Sub GetData(MaxSize)

' --------------------------------------

' 上传组件开关

' 参数:IsOpenUpLoad,1 = 打开,0 = 关闭

Const IsOpenUpLoad = 1

If IsOpenUpLoad <>1 Then Exit Sub

' --------------------------------------

Dim RequestBinData, sSpace, bCrLf, sInfo, iInfoStart, iInfoEnd, tStream, iStart, oFileInfo

Dim iFileSize, sFilePath, sFileType, sFormValue, sFileName

Dim iFindStart, iFindEnd

Dim iFormStart, iFormEnd, sFormName

If Request.TotalBytes <1 Then

Err = 1

Exit Sub

End If

If MaxSize >0 Then

If Request.TotalBytes >MaxSize Then

Err = 2

'Exit Sub

End If

End If

Set Form = Server.CreateObject("Scripting.Dictionary")

Form.CompareMode = 1

Set File = Server.CreateObject("Scripting.Dictionary")

File.CompareMode = 1

Set tStream = Server.CreateObject("ADODB.Stream")

Set oUpFileStream = Server.CreateObject("ADODB.Stream")

oUpFileStream.Type = 1

oUpFileStream.Mode = 3

oUpFileStream.Open

oUpFileStream.Write Request.BinaryRead(Request.TotalBytes)

oUpFileStream.Position = 0

RequestBinData = oUpFileStream.Read

iFormEnd = oUpFileStream.Size

bCrLf = ChrB(13) &ChrB(10)

sSpace = MidB(RequestBinData,1, InStrB(1,RequestBinData,bCrLf)-1)

iStart = LenB(sSpace)

iFormStart = iStart+2

Do

iInfoEnd = InStrB(iFormStart,RequestBinData,bCrLf &bCrLf)+3

tStream.Type = 1

tStream.Mode = 3

tStream.Open

oUpFileStream.Position = iFormStart

oUpFileStream.CopyTo tStream,iInfoEnd-iFormStart

tStream.Position = 0

tStream.Type = 2

tStream.CharSet = "utf-8"

sInfo = tStream.ReadText

iFormStart = InStrB(iInfoEnd,RequestBinData,sSpace)-1

iFindStart = InStr(22,sInfo,"name=""",1)+6

iFindEnd = InStr(iFindStart,sInfo,"""",1)

sFormName = Mid(sinfo,iFindStart,iFindEnd-iFindStart)

If InStr(45,sInfo,"filename=""",1) >0 Then

Set oFileInfo = new FileInfo_Class

iFindStart = InStr(iFindEnd,sInfo,"filename=""",1)+10

iFindEnd = InStr(iFindStart,sInfo,"""",1)

sFileName = Mid(sinfo,iFindStart,iFindEnd-iFindStart)

oFileInfo.FileName = Mid(sFileName,InStrRev(sFileName, "\")+1)

oFileInfo.FilePath = Left(sFileName,InStrRev(sFileName, "\"))

oFileInfo.FileExt = Mid(sFileName,InStrRev(sFileName, ".")+1)

iFindStart = InStr(iFindEnd,sInfo,"Content-Type: ",1)+14

iFindEnd = InStr(iFindStart,sInfo,vbCr)

oFileInfo.FileType = Mid(sinfo,iFindStart,iFindEnd-iFindStart)

oFileInfo.FileStart = iInfoEnd

oFileInfo.FileSize = iFormStart -iInfoEnd -2

oFileInfo.FormName = sFormName

file.add sFormName,oFileInfo

else

tStream.Close

tStream.Type = 1

tStream.Mode = 3

tStream.Open

oUpFileStream.Position = iInfoEnd

oUpFileStream.CopyTo tStream,iFormStart-iInfoEnd-2

tStream.Position = 0

tStream.Type = 2

tStream.CharSet = "utf-8"

sFormValue = tStream.ReadText

If Form.Exists(sFormName) Then

Form(sFormName) = Form(sFormName) &", " &sFormValue

Else

form.Add sFormName,sFormValue

End If

End If

tStream.Close

iFormStart = iFormStart+iStart+2

Loop Until (iFormStart+2) >= iFormEnd

RequestBinData = ""

Set tStream = Nothing

End Sub

End Class

Class FileInfo_Class

Dim FormName, FileName, FilePath, FileSize, FileType, FileStart, FileExt

Public Function SaveToFile(Path)

On Error Resume Next

Dim oFileStream

Set oFileStream = CreateObject("ADODB.Stream")

oFileStream.Type = 1

oFileStream.Mode = 3

oFileStream.Open

oUpFileStream.Position = FileStart

oUpFileStream.CopyTo oFileStream,FileSize

oFileStream.SaveToFile Path,2

oFileStream.Close

Set oFileStream = Nothing

End Function

Public Function FileData

oUpFileStream.Position = FileStart

FileData = oUpFileStream.Read(FileSize)

End Function

End Class

%>

服务器端servlet代码:

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//获取输入流,是HTTP协议中的实体内容

ServletInputStream sis=request.getInputStream()

File file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+0+".jpg")

for (int imgnum = 0file.exists()imgnum++)

{

file = new File(request.getSession().getServletContext().getRealPath("/img/"),"img_"+imgnum+".jpg")

}

//缓冲区

byte buffer[]=new byte[1024]

FileOutputStream fos=new FileOutputStream(file)

int len=sis.read(buffer, 0, 1024)

//把流里的信息循环读入到文件中

while( len!=-1 )

{

fos.write(buffer, 0, len)

len=sis.readLine(buffer, 0, 1024)

}

fos.close()

sis.close()

}

android客户端代码:

public static void uploadFile(String imageFilePath)

{

String actionUrl = "http://192.168.1.32:8080/UploadServer/ImageServlet"

try

{

URL url =new URL(actionUrl)

HttpURLConnection con=(HttpURLConnection)url.openConnection()

con.setDoInput(true)

con.setDoOutput(true)

con.setUseCaches(false)

con.setRequestMethod("POST")

DataOutputStream ds = new DataOutputStream(con.getOutputStream())

File file = new File(imageFilePath)

FileInputStream fStream = new FileInputStream(file)

int bufferSize = 1024

byte[] buffer = new byte[bufferSize]

int length = -1

while((length = fStream.read(buffer)) != -1)

{

ds.write(buffer, 0, length)

}

fStream.close()

ds.flush()

InputStream is = con.getInputStream()

int ch

StringBuffer b =new StringBuffer()

while( ( ch = is.read() ) != -1 )

{

b.append( (char)ch )

}

ds.close()

}

catch(Exception e)

{

e.printStackTrace()

}

}

前端 代码  使用 extjs 3.4

uploadPhotoWindow=Ext.extend(Ext.Window,{

title:" 上传图片  Upload  Photo",

height:420 ,

width:600,

closeAction:'close',

modal : true,

iconCls:'btn-setting',

buttonAlign: 'center',

upload_ok:false,

haveUpload:false,

initComponent : function() { 

Ext.form.Field.prototype.msgTarget = 'side'

  var po_no=new Ext.form.TextField({name:'Po_no',fieldLabel: '单号 Po No',itemId:'Po_no', width:120,

allowBlank: false, value:this.cur_sele_po_no, hidden:true}) 

var OP=new Ext.form.TextField({name:'OP',itemId:'OP', width:12,

allowBlank: false, value:"uploadphoto", hidden:true}) 

var file_name=new Ext.form.TextField({name:'photo_file_name',itemId:'photo_file_name', width:180,

allowBlank: false, value:"",hidden:true,}) 

var imagebox = new Ext.BoxComponent({

itemId:'imagebox',

autoEl: {

tag: 'img',    //指定为img标签 

style: 'height:100%margin:0px autoborder:1px solid #ccc text-align:centermargin-bottom:10px',

src: 'img/userimg/nophoto.jpg' ,   //指定url路径 

}

})

   var form_set_field = new Ext.FormPanel({

frame:true,

itemId:'form_set_field',

layout:'form', 

//tableAttrs: {border: 1},

defaults:{labelAlign:'right',labelWidth:110,bodyStyle: 'padding:0 30px 0 0',frame:false,layout:'form'},

items:[po_no,OP,file_name,imagebox],

}) 

var file = new  Ext.form.TextField({

              name: 'imgFile',

                  fieldLabel: '文件上传',

                  inputType: 'file',

                  allowBlank: false,

                  blankText: '请浏览图片'

})  

   var form_set_file = new Ext.FormPanel({

frame:true,

fileUpload: true,

itemId:'form_set_file',

layout:'form', 

//tableAttrs: {border: 1},

defaults:{labelAlign:'right',labelWidth:110,bodyStyle: 'padding:0 30px 0 0',frame:false,layout:'form'},

items:[file],

}) 

var btnOK= new Ext.Button({text: '上传 Upload  ', iconCls:'btn-save',width:70,handler: function(){

var form_set=this.ownerCt.ownerCt.getComponent('form_set_file')

var form_set_field=this.ownerCt.ownerCt.getComponent('form_set_field')

var po_no=form_set_field.getComponent('Po_no').getValue()

var file_name=form_set_field.getComponent('photo_file_name')

//alert(po_no)

var imgbox=form_set_field.getComponent('imagebox')

  if (form_set.getForm().isValid()){

form_set.getForm().submit({ 

waitMsg : '正在上传数据 Uploading....',waitTitle:'请稍候 waiting....',

url:'php/toolsfile/photoUpload.php', 

method : 'post', 

success : function(form, action){ 

var out = action.result.success 

if (out != true){

Ext.Msg.alert('提示 Tips ', '上传数据失败,错误信息   Save failure  :'+action.result.msg)

//alert(action.result.msg)

} else{

//Ext.Msg.alert('提示 Tips ', '上传数据成功,服务器信息: Save success '+action.result.msg)

file_name.setValue(action.result.file_name)

imgbox.getEl().dom.src=action.result.file_scr

form_set.ownerCt.savePhoto()

//form_set.ownerCt.grid.store.load()

//form_set.ownerCt.dateChang=true

//form_set.ownerCt.destroy( )

}

},

failure: function(form, action) {

switch (action.failureType) {  

case Ext.form.Action.CLIENT_INVALID:  

Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values')  

break  

case Ext.form.Action.CONNECT_FAILURE:  

Ext.Msg.alert('Failure', 'Ajax communication failed')  

break  

case Ext.form.Action.SERVER_INVALID:  

Ext.Msg.alert('Failure', action.result.msg)  

break

}  

},

}) 

}else{

Ext.Msg.alert('提示 Tips :', '请选择文件! \n Please select Img file ')

}

})

var btnCancel = new Ext.Button({text: ' 关闭  Close ', iconCls:'btn-cancel',width:70,handler: function(){this.ownerCt.ownerCt.destroy( )}})

Ext.apply(this,{

items: [form_set_field,form_set_file],

buttons: [btnOK,  btnCancel],

}) 

uploadPhotoWindow.superclass.initComponent.call(this) 

},

savePhoto:function (){

//alert(this.cur_sele_po_no)

var form_set_field=this.getComponent('form_set_field')

var form_set_file=this.getComponent('form_set_file')

form_set_field.getForm().submit({

waitMsg : '上传成功,正在存储 saveing....',waitTitle:'请稍候 waiting....',

url:'php/jsonfile/po_nophotolist_json.php', 

method : 'post', 

success : function(form, action){ 

var out = action.result.success 

if (out != true){

Ext.Msg.alert('提示 Tips ', '存储失败,错误信息   Save failure  :'+action.result.msg)

} else{

Ext.Msg.alert('提示 Tips ', '存储成功,服务器信息: Save success '+action.result.msg)

form_set_file.getForm().reset()

form_set_file.ownerCt.haveUpload=true

}

},

failure: function(form, action) {

switch (action.failureType) {  

case Ext.form.Action.CLIENT_INVALID:  

Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values')  

break  

case Ext.form.Action.CONNECT_FAILURE:  

Ext.Msg.alert('Failure', 'Ajax communication failed')  

break  

case Ext.form.Action.SERVER_INVALID:  

Ext.Msg.alert('Failure', action.result.msg)  

break

}  

},

})

},

isUpload:function(){

return this.haveUpload

}

})

后台php photoUpload.php'

<?

require_once('../classfile/guid.class.php')

if(!isset($_FILES['imgFile'])){

echo json_encode(array("success"=>false, 'msg'=>"Not get Imgfile"))

return

}

$upfile=$_FILES['imgFile']

$name=$upfile["name"]//上传文件的文件名 

$type=$upfile["type"]//上传文件的类型 

$size=$upfile["size"]//上传文件的大小 

$tmp_name=$upfile["tmp_name"]//上传文件的临时存放路径 

$error_cod=$upfile["error"]

 if ($error_cod>0){

echo json_encode(array("success"=>false, 'msg'=>$error_cod))

$ext_file_name=""

switch ($type){ 

case 'image/pjpeg':

$okType=true

$ext_file_name =".jpg"

break 

case 'image/jpeg':

$okType=true 

$ext_file_name =".jpg"

break 

case 'image/gif':

$okType=true 

$ext_file_name =".gif"

break 

case 'image/png':

$okType=true 

$ext_file_name =".png"

break 

if(!$okType){ 

echo json_encode(array("success"=>false, 'msg'=>"Not  image "))

return

}

$web_root="D:".DIRECTORY_SEPARATOR."Easy2PHP5".DIRECTORY_SEPARATOR."webSiteJfz".DIRECTORY_SEPARATOR

$photo_tmp_path=$web_root."img".DIRECTORY_SEPARATOR."userimg".DIRECTORY_SEPARATOR."temp"

$temp_file_name= creat_guid(0).$ext_file_name

$photo_tmp_file_name=$photo_tmp_path.DIRECTORY_SEPARATOR.$temp_file_name

$photo_tmp_file_scr="img".DIRECTORY_SEPARATOR."userimg".DIRECTORY_SEPARATOR."temp".DIRECTORY_SEPARATOR.$temp_file_name

move_uploaded_file($tmp_name,$photo_tmp_file_name) 

echo json_encode(array("success"=>true, 'msg'=> "ok","file_name"=>$photo_tmp_file_name,"file_scr"=>$photo_tmp_file_scr))

//echo json_encode(array("success"=>false, 'msg'=> json_encode($_FILES['imgFile'])))

return

?>

guid.class.php // 生成唯一的图片文件名

<?

function creat_guid($long){

$uuid=""

    if (function_exists('com_create_guid')){

        $uuid=com_create_guid()

    }else{

        mt_srand((double)microtime()*10000)//optional for php 4.2.0 and up.

        $charid = strtoupper(md5(uniqid(rand(), true)))

        $hyphen = chr(45)// "-"

        $uuid = chr(123)// "{"

.substr($charid, 0, 8).$hyphen

                .substr($charid, 8, 4).$hyphen

                .substr($charid,12, 4).$hyphen

                .substr($charid,16, 4).$hyphen

                .substr($charid,20,12)

                .chr(125)// "}"

        //return $uuid

    }

if (!isset($long) || $long==0 ){

return substr($uuid,1, strlen($uuid)-2)

}else{

return $uuid

}

}


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/243151.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-12
下一篇2023-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存