当前位置:首页 » 文件传输 » java上传视频文件到服务器
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

java上传视频文件到服务器

发布时间: 2022-05-15 02:24:56

① 如何利用java将本地文件上传到服务器

如果服务器开通了ftp服务,你的客户端可以实现一个ftp的客户端,通过ftp服务将文件上传到服务器的指定目录下,可以使用org.apache.commons.net.ftp.FTPClient这个类去实现,非常的简单,网上有很多现成的代码可以用

② java怎么把文件传输到服务器

String realpath = ServletActionContext.getServletContext().getRealPath("/upload") ;//获取服务器路径
String[] targetFileName = uploadFileName;
for (int i = 0; i < upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.File(upload[i], target);
//这是一个文件复制类File()里面就是IO操作,如果你不用这个类也可以自己写一个IO复制文件的类
}

其中private File[] upload;// 实际上传文件

private String[] uploadContentType; // 文件的内容类型

private String[] uploadFileName; // 上传文件名

这三个参数必须这样命名,因为文件上传控件默认是封装了这3个参数的,且在action里面他们应有get,set方法

③ java后台文件上传到资源服务器上

package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * 上传文件到服务器 * * @param file * 需要上传的文件 * @param RequestURL * 文件服务器的rul * @return 返回响应的内容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

④ java怎么将上传文件到别的服务器

首先,获得别的服务器的上传接口,然后做写上传程序的时候默认设置上传到该服务器。或者直接将java上传程序放在别的服务器,直接这里调用即可。

⑤ java 怎么上传视频 上传到服务器 然后再读

找个JAVA文件上传的包,或者用Struts的方法,文件存在服务器上,把URL记住,直接在网页上加载就OK

⑥ 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+" ");

  • }

  • 。。。。。。

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

⑦ java中怎么把文件上传到服务器的指定路径

文件从本地到服务器的功能,其实是为了解决目前浏览器不支持获取本地文件全路径。不得已而想到上传到服务器的固定目录,从而方便项目获取文件,进而使程序支持EXCEL批量导入数据。

java中文件上传到服务器的指定路径的代码:

在前台界面中输入:

<form method="post" enctype="multipart/form-data" action="../manage/excelImport.do">

请选文件:<input type="file" name="excelFile">

<input type="submit" value="导入" onclick="return impExcel();"/>

</form>

action中获取前台传来数据并保存

/**

* excel 导入文件

* @return

* @throws IOException

*/

@RequestMapping("/usermanager/excelImport.do")

public String excelImport(

String filePath,

MultipartFile excelFile,HttpServletRequest request) throws IOException{

log.info("<<<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" );

if (excelFile != null){

String filename=excelFile.getOriginalFilename();

String a=request.getRealPath("u/cms/www/201509");

SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename);//保存到服务器的路径

}

log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" );

return "";

}

/**

* 将MultipartFile转化为file并保存到服务器上的某地

*/

public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException

{

FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);

System.out.println("------------"+path + "/"+ savefile);

byte[] buffer =new byte[1024*1024];

int bytesum = 0;

int byteread = 0;

while ((byteread=stream.read(buffer))!=-1)

{

bytesum+=byteread;

fs.write(buffer,0,byteread);

fs.flush();

}

fs.close();

stream.close();

}

⑧ 怎样使用javaweb实现上传视频和下载功能

文件上传就是将客户端资源,通过网路传递到服务器端。

因为文件数据比较大,必须通过文件上传才可以完成将数据保存到数据库端的操作。

文件上传的本质就是IO流操作。

演示:文件上传应该如何操作?

浏览器端:
1.method=post 只有post才可以携带大数据
2.必须使用<input type='file' name='f'>要有name属性
3.encType="multipart/form-data"
服务器端:
request对象是用于获取请求信息。
它有一个方法 getInputStream(); 可以获取一个字节输入流,通过这个流,可以读取到
所有的请求正文信息.
文件上传原理:
浏览器端注意上述三件事,在服务器端通过流将数据读取到,在对数据进行解析.
将上传文件内容得到,保存在服务器端,就完成了文件上传。

注意:在实际开发中,不需要我们进行数据解析,完成文件上传。因为我们会使用文件上传的工具,它们已经封装好的,提供API,只要调用它们的API就可以完成文件上传操作.我们使用的commons-fileupload,它是apache提供的一套开源免费的文件上传工具。

代码演示文件上传的原理:

在WebRoot下新建upload1.jsp

[html]view plain

  • <%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>

  • <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">

  • <html>

  • <head>

  • <title>MyJSP'index.jsp'startingpage</title>

  • </head>

  • <body>

  • <!--encType默认是application/x-www-form-urlencoded-->

  • <formaction="${pageContext.request.contextPath}/upload1"

  • method="POST"enctype="multipart/form-data">

  • <inputtype="text"name="content"><br>

  • <inputtype="file"name="f"><br><inputtype="submit"

  • value="上传">

  • </form>

  • </body>

  • </html>

  • 新建Upload1Servlet 路径:/upload1

    [java]view plain

  • packagecn.itcast.web.servlet;

  • importjava.io.IOException;

  • importjava.io.InputStream;

  • importjavax.servlet.ServletException;

  • importjavax.servlet.http.HttpServlet;

  • importjavax.servlet.http.HttpServletRequest;

  • importjavax.servlet.http.HttpServletResponse;

  • {

  • publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)

  • throwsServletException,IOException{

  • //System.out.println("upload1servlet......");

  • //通过request获取一个字节输入流,将所有的请求正文信息读取到,打印到控制台

  • InputStreamis=request.getInputStream();

  • byte[]b=newbyte[1024];

  • intlen=-1;

  • while((len=is.read(b))!=-1){

  • System.out.println(newString(b,0,len));

  • }

  • is.close();

  • }

  • publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)

  • throwsServletException,IOException{

  • doGet(request,response);

  • }

  • }

  • 在浏览器端访问信息如下:


    文件上传概述

    实现web开发中的文件上传功能,需要完成如下二步操作:

  • 在web页面中添加上传输入项。

  • 在Servlet中读取上传文件的数据,并保存在服务器硬盘中。

  • 如何在web页面中添加上传输入项?

    <input type="file">标签用于在web页面中添加文件上传输入项,设置文件上传输入项时注意:

  • 1、必须设置input输入项的name属性,否则浏览器将不会发送上传文件的数据。

  • 2、必须把form的encType属性设为multipart/form-data 设置该值后,浏览器在上传文件时,并把文件数据附带在http请求消息体内,并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。

  • 3、表单的提交方式要设置为post。

  • 如何在Servlet中读取文件上传数据,并保存到本地硬盘中?

  • Request对象提供了一个getInputStream方法,通过这个方法可以读取到客户端提交过来的数据。但由于用户可能会同时上传多个文件,在servlet端编程直接读取上传数据,并分别解析出相应的文件数据是一项非常麻烦的工作,示例。

  • 为方便用户处理文件上传数据,Apache 开源组织提供了一个用来处理表单文件上传的一个开源组件( Commons-fileupload ),该组件性能优异,并且其API使用极其简单,可以让开发人员轻松实现web文件上传功能,因此在web开发中实现文件上传功能,通常使用Commons-fileupload组件实现。

  • 使用Commons-fileupload组件实现文件上传,需要导入该组件相应支撑jar包:Commons-fileupload和commons-io。commo-io不属于文件上传组件的开发jar文件,但Commons-fileupload组件从1.1版本开始,它工作时需要commons-io包的支持。

⑨ java客户端怎么把本地的文件上传到服务器

String realpath = ServletActionContext.getServletContext().getRealPath("/upload") ;//获取服务器路径
String[] targetFileName = uploadFileName;
for (int i = 0; i < upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.File(upload[i], target);
//这是一个文件复制类File()里面就是IO操作,如果你不用这个类也可以自己写一个IO复制文件的类
}

其中private File[] upload;// 实际上传文件

private String[] uploadContentType; // 文件的内容类型

private String[] uploadFileName; // 上传文件名

这三个参数必须这样命名,因为文件上传控件默认是封装了这3个参数的,且在action里面他们应有get,set方法

⑩ java web怎么实现文件上传到服务器

/**
* 上传到本地
* @param uploadFile
* @param request
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public Map<String, Object> uploadApkFile(@RequestParam("uploadUpdateHistoryName") MultipartFile uploadFile,
HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
// 上传文件校验,包括上传文件是否为空、文件名称是否为空、文件格式是否为APK。
if (uploadFile == null) {
map.put("error", 1);
map.put("msg", "上传文件不能为空");
return map;
}
String originalFilename = uploadFile.getOriginalFilename();
if (StringUtils.isEmpty(originalFilename)) {
map.put("error", 1);
map.put("msg", "上传文件名称不能为空");
return map;
}
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (extName.toUpperCase().indexOf("APK") < 0) {
map.put("error", 1);
map.put("msg", "上传文件格式必须为APK");
return map;
}

String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = uploadFile.getOriginalFilename();
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
String downLoadUrl = null;
try {
uploadFile.transferTo(targetFile);
downLoadUrl = request.getContextPath() + "/upload/" + fileName;
map.put("error", 0);
map.put("downLoadUrl", downLoadUrl);
map.put("msg", "上传文件成功");
return map;
} catch (Exception e) {
e.printStackTrace();
map.put("error", 1);
map.put("msg", "上传文件失败");
return map;
}
}

//上传文件
$('#btnUpload').bind('click',function(){
// var formdata= $('#uploadForm').serializeJSON();
var formdata = new FormData($( "#uploadForm" )[0]);
$.ajax({
url:"upload.do",
data:formdata,
async: false,
cache: false,
processData:false,
contentType:false,
// dataType:'json',
type:'post',
success:function(value){
if(value.error==0){
$('#downLoadUrlId').val(value.downLoadUrl);
$.messager.alert('提示',value.msg);
$('#uploadWindow').window('close');
}else{
$.messager.alert('提示',value.msg);
}
}
});
});

<div id="uploadWindow" class="easyui-window" title="apk上传"
style="width: 230px;height: 100px" data-options="closed:true">
<form id="uploadForm" enctype="multipart/form-data">
<td><input type ="file" style="width:200px;" name = "uploadUpdateHistoryName"></td>
</form>
<button id="btnUpload" type="button">上传Apk</button>
</div>

java js html