首页 > 编程语言 >javaweb文件上传和下载

javaweb文件上传和下载

时间:2022-10-09 18:04:05浏览次数:54  
标签:collapse song String var new 上传 bis 下载 javaweb


案例1:

文件随同表单一起上传

前端页面

<div>
<form class="form-signin" id="addSongFormId" enctype="multipart/form-data" method="post">
歌曲:
<input type="file" id="fileSongId" class="custom-file-input"
name="song">
歌手:
<input type="text" class="form-control mr-sm-2"
name="songAuthor">
类型:

<select class="custom-select-override " name="songLanguageType">
<option value="1">华语</option>
<option value="2">日韩</option>
<option value="3">欧美</option>
</select>
</form>
</div>

js代码

<script>
$(function () {
//处理上传
var maxSongSize = 1024 * 1024 * 20;//文件最大10M
var songFormat = ["mp3"];
$("#addSongFormId").submit(function () {
var song = $('#fileSongId').get(0).files[0];
//判定格式
if (song == null) {
$('#collapse-file-error-hint').html("请选择歌曲文件");
$('#collapse-file-error-hint').collapse();
return false;
} else if (song.size > maxSongSize) {
$('#collapse-file-error-hint').html("超出文件最大限制");
$('#collapse-file-error-hint').collapse();
return false;
} else if (songFormat.indexOf(song.name.substr(song.name.lastIndexOf(".") + 1)) == -1) {
$('#collapse-file-error-hint').html("歌曲文件格式不对");
$('#collapse-file-error-hint').collapse();
return false;
} else {
}
//提交
url = "frontaddSong";
/**
* var data=$('#addSongFormId').serialize();
* 序列化的方式,表单里有文件的时候就不行了,可以用FormData对象
*/
var data = new FormData(document.getElementById("addSongFormId"));
//var data = new FormData($('#addSongFormId'));
$.ajax({
type: "POST",
url: url,
data: data,
processData: false,
contentType: false,
success: function (data) {
var res = JSON.parse(data);
if (res.status == 200) {
$('#collapse-file-error-hint').html(res.msg);
$('#collapse-file-error-hint').collapse()
alert("上传成功");
$("#UpModalCenter").modal('hide');
// window.location.reload();
$('#list-upload').load("uploadFrameLoad.do");
} else {
$('#collapse-file-error-hint').html(res.msg);
$('#collapse-file-error-hint').collapse()
}
}
});
return false;

});//处理上传 End

});
</script>

后台代码:

/**
* 添加歌曲
*
* @param request
* @param song
* @return
*/
@PostMapping(value = "frontaddSong")
@ResponseBody
public String addSong(HttpServletRequest request, String songAuthor,
Integer songLanguageType, MultipartFile song) {
String name = song.getOriginalFilename();
//歌曲名称需去掉.mp3的后缀
String songName = name.substring(0, name.lastIndexOf("."));
//这里上传至webapp下的track/song文件夹下
String songAddress = "track/song/" + name;
User user = (User) request.getSession().getAttribute("user");
Song song1 = new Song(songName, songAddress, songLanguageType, 1,
0, user.getUserId(), songAuthor, 0, 0);
int result = songDao.insertOnlySong(song1);
if (result > 0) {
saveFile(song, request.getServletContext().getRealPath(songAddress));
return ReturnMsg.msg(HttpServletResponse.SC_OK, "上传成功");
} else {
return ReturnMsg.msg(HttpServletResponse.SC_BAD_GATEWAY, "上传失敗");
}
}

private void saveFile(MultipartFile multipartFile, String realFilePath) {
try {
//使用输入输出缓冲流提高上传效率
InputStream fis = multipartFile.getInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(realFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int size = 0;
byte[] buffer = new byte[10240];
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
//刷新此缓冲的输出流,保证数据全部都能写出
bos.flush();
bis.close();
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}

文件下载

//download.do?songAddress=track/song/毛不易 - 无问.mp3&songId=290
@RequestMapping(value = "download.do", method = { RequestMethod.GET})
public void download(HttpServletRequest request,HttpServletResponse response,String songAddress,int songId) throws IOException {
response.setContentType("audio/mp3");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(System.currentTimeMillis()+"如果不想返回名称的话.mp3", "utf8"));
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
InputStream bis=null;
if(songAddress.contains("http")) {
//在另外服务器的文件
URL url = new URL(songAddress);
URLConnection uc = url.openConnection();
bis=new BufferedInputStream(uc.getInputStream());
}else {
//在服务器内部的文件
songAddress=request.getServletContext().getRealPath(songAddress);
bis = new BufferedInputStream(new FileInputStream(new File(songAddress)));
}
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
bis.close();
}

案例二:

读写指定路径的文件

public static void main(String[] args){
/**
* 1.先将文件中的内容读入到缓冲输入流中
* 2.将输入流中的数据通过缓冲输出流写入到目标文件中
* 3.关闭输入流和输出流
*/
try {
long begin=System.currentTimeMillis();
FileInputStream fis=new FileInputStream("BISDemo.txt");
BufferedInputStream bis=new BufferedInputStream(fis);

FileOutputStream fos=new FileOutputStream("BOSDemo.txt");
BufferedOutputStream bos=new BufferedOutputStream(fos);

int size=0;
byte[] buffer=new byte[10240];
while((size=bis.read(buffer))!=-1){
bos.write(buffer, 0, size);
}
//刷新此缓冲的输出流,保证数据全部都能写出
bos.flush();
bis.close();
bos.close();
long end=System.currentTimeMillis();
System.out.println("使用缓冲输出流和缓冲输入流实现文件的复制完毕!耗时:"+(end-begin)+"毫秒");
} catch (Exception e) {
e.printStackTrace();
}
}

案例三:springmvc中后台如何接受上传文件方法

private void saveFile(MultipartFile multipartFile, String realFilePath) {
try {
InputStream fis = multipartFile.getInputStream();
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(realFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int size = 0;
byte[] buffer = new byte[10240];
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
//刷新此缓冲的输出流,保证数据全部都能写出
bos.flush();
bis.close();
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}

案例四:异步上传文件

表单html

<form id="addcropform" class="add-article-form" enctype="multipart/form-data">
<input type="hidden" value="${crop.id}" name="id">
<div class="col-md-9">
<h1 class="page-header">农作物编辑</h1>
<div class="form-group">
<p style="font-size: 16px;margin-bottom: 5px;">农作物名称</p>
<input type="text" id="title" name="title" value="${crop.title}" class="form-control"
required="required" placeholder="名称">
</div>
<div class="form-group">
<label for="category-fname">农作物类别</label>
<select id="category-fname" class="form-control" name="typeid"
style="width: 240px;margin-bottom: 10px">
<option value="">请选择</option>
<c:forEach items="${types}" var="t">
<c:if test="${t.parentid==1}">
<option value="${t.id}" ${crop.typeid==t.id?'selected' : ''}>${t.name}</option>
</c:if>
</c:forEach>
</select>
</div>
<div class="form-group">
<p style="font-size: 16px;margin-bottom: 5px;">特性</p>
<input type="text" name="feature" value="${crop.feature}" class="form-control"
placeholder="特性"
required="required">
</div>
<div class="form-group">
<p style="font-size: 16px;margin-bottom: 5px;">生长环境</p>
<input type="text" name="environment" value="${crop.environment}" class="form-control"
placeholder="生长环境"
required="required">
</div>
<div class="form-group">
<p style="font-size: 16px;margin-bottom: 5px;">产地</p>
<input type="text" name="location" value="${crop.location}" class="form-control"
placeholder="产地"
required="required">
</div>
<div class="form-group">
<p style="font-size: 16px;margin-bottom: 5px;">图片</p>
<img src="<%=path %>${crop.img}" style="width: 80px;">
<input type="file" name="img" value="<%=path %>${crop.img}">
</div>

<div class="form-group">
<div id="editor" class="layui-input-block" style="background: white;">
<p>${crop.info}</p>
</div>
<div class="layui-input-block">
<textarea style="width:700px;height:100px;visibility:hidden;" name="info"
id="text1"></textarea>
</div>
<script type="text/javascript">
var E = window.wangEditor;
var editor = new E('#editor');
// 或者 var editor = new E( document.getElementById('editor') )
editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片
var $text1 = $('#text1')
editor.customConfig.onchange = function (html) {
// 监控变化,同步更新到 textarea
$text1.val(html)
}
editor.create();
$text1.val(editor.txt.html());
</script>
</div>
</div>
<div class="col-md-3">
<h1 class="page-header">操作</h1>
<div class="add-article-box-footer">
<button class="btn btn-primary" type="button" onclick="addCrop()" name="submit">发布
</button>
</div>
</div>
</form>

js代码

<script>
function addCrop() {
var title = $("#title").val();
if (!title) {
alert("名称不能为空");
return;
}
var formdata = new FormData($("#addcropform")[0]);
$.ajax({
type: "POST",//方法类型
dataType: "json",//预期服务器返回的数据类型
url: "/admin/addcrop",//url
data: formdata,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
console.log(result);//打印服务端返回的数据(调试用)
if (result.status == 200) {
alert("提交成功");
window.location.reload();
} else {
alert(result.msg);
}
},
error: function () {
alert("异常!");
}
});
}
</script>

后端代码

@ResponseBody
@PostMapping("/addcrop")
public Result addcrop(Integer id, HttpServletRequest request, String title, String info,
Integer typeid, String feature, String location,
String environment, @RequestParam("img") MultipartFile img) throws IOException {
if (id != null) {
//修改
String fileName = null;
if (!img.isEmpty()) {
//根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
fileName = System.currentTimeMillis() + img.getOriginalFilename();
//通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名,这个是web项目情况 如果是jar项目,不能使用这个
String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName;
File destFile = new File(destFileName);
//把浏览器上传的文件复制到希望的位置
img.transferTo(destFile);
//6.把文件名放在model里,以便后续显示用
}
Crop crop=null;
if(img.getOriginalFilename().equals("")){
crop = new Crop(id, title, null, info, new Date(),
typeid, feature, location, environment);
}else{
crop = new Crop(id, title, "/upload/" + fileName, info, new Date(),
typeid, feature, location, environment);
}

cropMapper.updateByPrimaryKey(crop);
return new Result(200);
} else {//添加
String fileName = null;
if (!img.isEmpty()) {
//根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了
fileName = System.currentTimeMillis() + img.getOriginalFilename();
//通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名
String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName;
File destFile = new File(destFileName);
//把浏览器上传的文件复制到希望的位置
img.transferTo(destFile);
}
Crop crop = new Crop(id, title, "/upload/" + fileName, info, new Date(),
typeid, feature, location, environment);
cropMapper.insert(crop);
return new Result(200);
}
}

 

 

标签:collapse,song,String,var,new,上传,bis,下载,javaweb
From: https://blog.51cto.com/u_11334685/5740987

相关文章

  • Thmeleaf.pdf下载使用
    1、如何使用springboot整合2、书籍下载链接:​​https://pan.baidu.com/s/19y_1U3kBvh0r-Qn9ZS7mDg​​提取码:q7s23、常用总结a连接带参数请求的两种方式第一种:通过拼接字符......
  • 解决curl下载夹带中文的文件
    1.提供代码重点关注curl_escapeAPI#include<stdlib.h>#include<stdio.h>#include<sys/stat.h>#include<curl/curl.h>size_tgetcontentlengthfunc(void*p......
  • Anaconda下载安装
    下载地址:链接:https://pan.baidu.com/s/1fmJkMSL6amJF4KP5JwklOQ提取码:dsyc安装完成之后,记得配置系统环境变量:......
  • SSTap 下载安装使用图文教程(网游)加速器
    简介SSTap全称SOCKSTap,是一款利用虚拟网卡技术在网络层实现的代理工具,SSTap能在网络层拦截所有连接并转发给SSR/SS,而无需对被代理的应用程序做任何修改或设置。它能同时......
  • a标签下载图片,不要预览
    constdownloadhandler=()=>{constlink=document.createElement('a')//这里是将url转成blob地址将链接地址字符内容转变成blob地址fetch(icoUrl).then......
  • EasyNVR下载安装后页面无法登录是什么原因?
    EasyNVR平台基于RTSP/Onvif协议,可支持设备接入、视频流处理及分发等功能,在视频监控场景中可实现视频实时监控直播、云端录像、云存储、录像检索与回看、告警、级联等,极大满......
  • Visual Studio Code下载
      最近在官网下载VisualStudioCode时,下载速度特别慢,经过搜索后发现,将下载地址前部分更换为国内地址后,下载速度飞快。  具体步骤如下:        ......
  • MySQL的下载与安装
    ......
  • docker 下nginx 实现文件下载
     1、新建目录存放文件 2、将目录挂载到容器,新增配置如下  3、nginx配置文件新增配置location~*(.*.apk){#代理后缀为apk的文件add_h......
  • VS2019 下载NUGet包 本地安装 但没有成功
    1、下载:在网址https://www.nuget.org/中找对应的包版本 2、新建程序包源地址,其地址设置为下载的本地包地址:E:\NuGet离线包;点击更新   3、在程序包管理控制......