导航:首页 > IDC知识 > java图片上传服务器

java图片上传服务器

发布时间:2020-11-07 20:47:48

1、java通过图片的名字上传到服务器的方法

提交页面表单
<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"%>
<%

2、java上传图片到远程服务器上,怎么解决呢?

需要这样的一个包 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();}
}
}

3、java怎么实现上传文件到服务器

common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件

下面先介绍上传文件到服务器(多文件上传):

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

import java.util.regex.*;

import org.apache.commons.fileupload.*;


public class upload extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=GB2312";

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(CONTENT_TYPE);

PrintWriter out=response.getWriter();

try {

DiskFileUpload fu = new DiskFileUpload();

 // 设置允许用户上传文件大小,单位:字节,这里设为2m

 fu.setSizeMax(2*1024*1024);

 // 设置最多只允许在内存中存储的数据,单位:字节

 fu.setSizeThreshold(4096);

 // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

 fu.setRepositoryPath("c://windows//temp");

 //开始读取上传信息

 List fileItems = fu.parseRequest(request);

 // 依次处理每个上传的文件

 Iterator iter = fileItems.iterator();

//正则匹配,过滤路径取文件名

 String regExp=".+////(.+)$";

//过滤掉的文件类型

String[] errorType={".exe",".com",".cgi",".asp"};

 Pattern p = Pattern.compile(regExp);

 while (iter.hasNext()) {

 FileItem item = (FileItem)iter.next();

 //忽略其他不是文件域的所有表单信息

 if (!item.isFormField()) {

 String name = item.getName();

 long size = item.getSize();

 if((name==null||name.equals("")) && size==0)

 continue;

 Matcher m = p.matcher(name);

 boolean result = m.find();

 if (result){

 for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){

 if (m.group(1).endsWith(errorType[temp])){

 throw new IOException(name+": wrong type");

 }

 }

 try{

//保存上传的文件到指定的目录

//在下文中上传文件至数据库时,将对这里改写

 item.write(new File("d://" + m.group(1)));

out.print(name+"  "+size+"");

 }

 catch(Exception e){

 out.println(e);

 }

}

 else

 {

 throw new IOException("fail to upload");

 }

 }

 }

}

 catch (IOException e){

 out.println(e);

 }

 catch (FileUploadException e){

out.println(e);

 }

 

}

}

现在介绍上传文件到服务器,下面只写出相关代码:

以sql2000为例,表结构如下:

字段名:name  filecode

类型: varchar image

数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");

代码如下:

。。。。。。

try{

这段代码如果不去掉,将一同写入到服务器中

//item.write(new File("d://" + m.group(1)));

 

int byteread=0;

//读取输入流,也就是上传的文件内容

InputStream inStream=item.getInputStream();  

pstmt.setString(1,m.group(1));

pstmt.setBinaryStream(2,inStream,(int)size);

pstmt.executeUpdate();

inStream.close();

out.println(name+"  "+size+" ");

}

。。。。。。

这样就实现了上传文件至数据库

4、java如何实现上传图片到服务器,并预览图片

预览,不能简单的用<img>,然后把地址赋给src的,会出现浏览器不兼容问题
用css滤镜,像下面
document.getElementById("previewImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + o.value + "')";
至于如何上传,struts2很方便的

5、java 如何只通过后台把本地的图片上传的服务器上去

import java.io.*;
public class CopyIMG{
    public static void main(String[] args)throws Exception{
        File file = new File("C:\xx.jpg");
        if(!file.exists())
            throw new RuntimeException("文件不存在..");
        FileInputStream fis = new FileInputStream(file);
        byte[] b = new byte[1024];
        int len = 0;
        FileOutputStream fos = new FileOutStream("要保存的服务器路径");
        while((len=is.read(b))!=-1){
            fos.write(b,0,len);
        }
        fos.close();
        fis.close();
    }
}

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

我们使用一些已有的组件帮助我们实现这种上传功能。
常用的上传组件:
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);
}

7、java上传图片到服务器指定路径

        private File myFile; //文件
private String myFileContentType; //类型
private String myFileFileName;    //文件名
//。。。。getXXX() setXXX()方法

//输入流
InputStream is = new FileInputStream(myFile);
//设定文件路径
String photoPath = ServletActionContext.getServletContext()
.getRealPath("/user/photo/");
File filePhotoPath = new File(photoPath);
//判断这个路径是否存在,如果不存在创建这个路径
if (!filePhotoPath.isDirectory()) {
filePhotoPath.mkdir();
}

String extension = FilenameUtils.getExtension(this
.getMyFileFileName());   //后缀名 比如jpg
String filename = UUID.randomUUID().toString() + "." + extension;

// 目标文件
File tofile = new File(photoPath, filename);
// 输出流
OutputStream os = new FileOutputStream(tofile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
// 关闭输入流
is.close();
// 关闭输出流
os.close();

8、java中怎么将本地图片上传到服务器上

服务器端,做一个FTP,客户端使用APACHE的FTP组件上传。。。。。。。



服务器端实现HTTP的POST接收,,,,,客户端使用httpclient组件post上去

与java图片上传服务器相关的知识