java 中如何向服务器上传图片

Python017

java 中如何向服务器上传图片,第1张

我们使用一些已有的组件帮助我们实现这种上传功能。

常用的上传组件:

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)

}

这里你弄错了一个问题\x0d\x0a你的程序是要传递图片的二进制数据.\x0d\x0a而不是传递路径,然后再到服务器读取文件数据(你的服务器有这个文件?)\x0d\x0a只有当你的服务器下有这个文件了,你传递一个路径,读取是可以的.\x0d\x0a//---\x0d\x0a关于如何上传文件, 自己google一下,很多教程

需要这样的一个包 jcifs-1.1.11

public static void forcdt(String dir){

InputStream in = null

OutputStream out = null

File localFile = new File(dir)

try{

//创建file类 传入本地文件路径

//获得本地文件的名字

String fileName = localFile.getName()

//将本地文件的名字和远程目录的名字拼接在一起

//确保上传后的文件于本地文件名字相同

SmbFile remoteFile = new SmbFile("smb://administrator:[email protected]/e$/aa/")

//创建读取缓冲流把本地的文件与程序连接在一起

in = new BufferedInputStream(new FileInputStream(localFile))

//创建一个写出缓冲流(注意jcifs-1.3.15.jar包 类名为Smb开头的类为控制远程共享计算机"io"包)

//将远程的文件路径传入SmbFileOutputStream中 并用 缓冲流套接

out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile+"/"+fileName))

//创建中转字节数组

byte[] buffer = new byte[1024]

while(in.read(buffer)!=-1){//in对象的read方法返回-1为 文件以读取完毕

out.write(buffer)

buffer = new byte[1024]

}

}catch(Exception e){

e.printStackTrace()

}finally{

try{

//注意用完操作io对象的方法后关闭这些资源,走则 造成文件上传失败等问题。!

out.close()

in.close()

}catch(Exception e){

e.printStackTrace()}

}

}