关于文件上传服务器的知识,前端是type = “file”标签,有预览功能

前端html

<div class="layui-col-md10" style="text-align: center;">
<label class = "layui-btn">
请上传图片
<input type="file" name="file10" id="pushBodyImgUrl10" value='img' onchange="UI.pushBodyImg()" style="display: none"/>
</label>
<div style="margin-top: 2%">
<button onclick="UI.clearImg()" class="layui-btn">清空</button>
<button onclick="UI.pushImgToAll()" class="layui-btn">群发</button>
</div>
<div style="text-align: center">
<br><br>
<img src="" id="img01" width="350" class="hide" value=""/>
</div>
</div>

JS:
//将图片上传
pushBodyImg:function(){
var file = $("#pushBodyImgUrl10")[0].files[0];
var objUrl = UI.getObjectURL(file);
//var objUrl = $("#pushBodyImgUrl10")[0].files[0];
var size = $("#pushBodyImgUrl10")[0].files[0].size;
console.log("size = "+size) ;
console.log("objUrl = "+objUrl) ;
if (objUrl)
{
$("#img01").attr("src", objUrl);//进行图片预览
console.log("objUrl = "+objUrl) ;
$("#img01").removeClass("hide");
}
},
//得到图片的Blob格式,兼容不同的浏览器
getObjectURL:function(file){
var url = null ;
if (window.createObjectURL!=undefined)
{ // basic
url = window.createObjectURL(file) ;
}
else if (window.URL!=undefined)
{
// mozilla(firefox)
url = window.URL.createObjectURL(file) ;
}
else if (window.webkitURL!=undefined) {
// webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;

},
//清空现有图片
clearImg:function(){
$("#pushBodyImgUrl10").val("");
$("#img01")[0].src="";
$("#img01").addClass("hide");
},
//进行图片上传
pushImgToAll:function() {
var title = $("#img01")[0].src;
var bodyImg = $("#pushBodyImgUrl10").val();
if(bodyImg ==''){
layui.layer.alert("请先上传图片");
return false;
}
var sizeImg = $("#pushBodyImgUrl10")[0].files[0].size;
var nameImg = bodyImg;
var sfIndexImg=nameImg.lastIndexOf(".");//后缀位置的.的位置
var extImg=nameImg.substring(sfIndexImg,nameImg.length).toUpperCase();//截取后缀
if(extImg !='.PNG' && extImg !='.GIF' && extImg !='.JPG' && extImg !='.JPEG' && extImg !='.BMP'){
layui.layer.alert("文件类型错误,请上传正确图片类型(png、gif、jpg、jpeg、bmp)");
return false;
}
if(sizeImg/1024/1024>5){
layui.layer.alert("图片大小不能大于5M");
return false;
}
var img = $("#pushBodyImgUrl10")[0].files[0];
var formData = new FormData();
formData.append("file",img);//这个是一个参数
$.ajax({
url : '/mp/filesToAll',
method : 'POST',
processData: false,
contentType:false,
data : formData,
success : function(result) {
if (result.resultCode == 1) {
layui.layer.alert("群发成功");
$("#pushBodyImgUrl10").val("");
$("#img01")[0].src="";
$("#img01").addClass("hide");
} else {
layui.layer.alert("群发失败");
}
}
})
},

后端JAVA
@RequestMapping(value="/filesToAll")
@ResponseBody
public JSONMessage imgToAll(HttpServletResponse response, @RequestParam(required = false)MultipartFile file){
String domain=appConfig.getUploadDomain();
String title = "";
String extImg = "";
if (file != null){
String uploadFileUrl = FileUtil.fileToUploadDomain(domain,file);
title = uploadFileUrl;
int sfIndexImg=title.lastIndexOf(".");//后缀位置的.的位置
extImg=title.substring(sfIndexImg,title.length()).toUpperCase();
}
User user = getUser();
List<Fans> fansList = getFriendsManager().getFansList(getUser().getUserId());
List<Integer> toUserIdList = Lists.newArrayList();
for (Fans fans : fansList) {
toUserIdList.add(fans.getToUserId());
}
MessageBean mb = new MessageBean();
mb.setContent(title);
mb.setFromUserId(user.getUserId() + "");
mb.setFromUserName(user.getNickname());
mb.setTimeSend(DateUtil.currentTimeSeconds());
mb.setMsgType(2);// 广播消息
if(extImg.equalsIgnoreCase(".mp4")){
mb.setType(6);//type是6表明是视频
}else{
mb.setType(2);//type是2表明是图片
}
mb.setMessageId(StringUtil.randomUUID());
try {
ThreadUtil.executeInThread(new Callback() {
@Override
public void execute(Object obj) {
KXMPPServiceImpl.getInstance().send(mb,toUserIdList);//给各个用户发消息
}
});
} catch (Exception e) {
System.out.println(user.getUserId() + ":推送失败");
return JSONMessage.failure(e.getMessage());
}
return JSONMessage.success();
}

public static String fileToUploadDomain(String domain,MultipartFile multipartFile){
String newUrl=null;
try {
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9";
// 服务器的域名
URL url = new URL(domain+"/upload/UploadServlet");//通过form表单生成上传到服务器的绝对路径
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 上传文件
String fileRealName = multipartFile.getOriginalFilename();//获得原始文件名;
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// 文件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-data;name=\"photo\";filename=\"" + fileRealName + "\"" + newLine);
sb.append("Content-Type:application/octet-stream");
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 将参数头的数据写入到输出流中
out.write(sb.toString().getBytes());
// 数据输入流,用于读取文件数据
DataInputStream in = new DataInputStream(multipartFile.getInputStream());
byte[] bufferOut = new byte[1024];
int bytes = 0;
// 每次读1KB数据,并且将文件数据写入到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
// 最后添加换行
out.write(newLine.getBytes());
in.close();
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine).getBytes();
// 写上结尾标识
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));//POST请求upload服务
//对Json response进行解析
JSONObject resultObj = JSON.parseObject(reader.readLine());
JSONObject resultData= resultObj.getJSONObject("data");
if(null == resultData)
throw new ServiceException("源文件不存在");
JSONArray data = resultData.getJSONArray("images");
if(resultData.getJSONArray("images").size()!=0){
data = resultData.getJSONArray("images");
}else if(resultData.getJSONArray("videos").size()!=0){
data = resultData.getJSONArray("videos");
}else if(resultData.getJSONArray("audios").size()!=0){
data = resultData.getJSONArray("audios");
}else if(resultData.getJSONArray("others").size()!=0){
data = resultData.getJSONArray("others");
}

if (data.size() > 0){
JSONObject imageData = data.getJSONObject(0);
newUrl = imageData.getString("oUrl");//"tUrl"
System.out.println(" upload new Url =====>"+newUrl);
return newUrl;//图片视频在服务器上的绝对路径,可以将该路径上传到客户端,客户端可现实该视频和图片
}

} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return newUrl;
}

//uploadServlet form表单上传的类
@WebServlet("/upload/UploadServlet")
public class UploadServlet extends BaseServlet {
private static final long serialVersionUID = 1L;

public UploadServlet() {
super();
}

@Override
protected JMessage hander(HttpServletRequest request, HttpServletResponse response) {
long start = System.currentTimeMillis();
DiskFileItemFactory factory = new DiskFileItemFactory(1000 * 1024 * 1024, new File(getSystemConfig().getuTemp()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> multipart = null;

JMessage jMessage = null;
int totalCount = 0;
// int uploadFlag = 0;
long userId = 0;
double validTime = 0;
try {
multipart = fileUpload.parseRequest(request);
for (FileItem item : multipart) {
if (item.isFormField()) {
if ("validTime".equals(item.getFieldName())) {
try {
validTime = Double.valueOf(item.getString());
} catch (NumberFormatException e) {
validTime = new Double(-1);
}
}
if ("userId".equals(item.getFieldName())) {
userId = Long.parseLong(item.getString());
}
} else {
if (item.getSize() > 0) {
totalCount++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (null == multipart) {
jMessage = new JMessage(1020101, "表单解析失败");
}
// else if (0 == uploadFlag) {
// jMessage = new JMessage(1010101, "缺少上传标记");
// }
else if (0 == totalCount) {
jMessage = new JMessage(1010101, "缺少上传文件");
}
if (null != jMessage)
return jMessage;
if (1 == getSystemConfig().getIsOpenfastDFS()) {
jMessage = fastDFSHander(multipart, validTime);
} else
jMessage = defHander(multipart, userId, validTime);

int successCount = jMessage.getIntValue("success");
jMessage.put("total", totalCount);
jMessage.put("failure", totalCount - successCount);
jMessage.put("time", System.currentTimeMillis() - start);

return jMessage;
}

protected JMessage fastDFSHander(List<FileItem> multipart, double validTime) {
JMessage message = null;
int successCount = 0;
List<UploadItem> images = Lists.newArrayList();
List<UploadItem> audios = Lists.newArrayList();
List<UploadItem> videos = Lists.newArrayList();
List<UploadItem> others = Lists.newArrayList();
String oUrl = null;
String tUrl = null;
for (FileItem item : multipart) {
UploadItem uploadItem;
if (item.isFormField() || item.getSize() < 1)
continue;
String fileName = item.getName();
String formatName = getFormatName(fileName);

FileType fileType = getFileType(formatName);
String path = uploadToFastDFS(item, validTime);
if (StringUtils.isEmpty(path))
continue;
oUrl = path;
tUrl = path;
successCount++;
if (FileType.Image == fileType) {//图片
try {
uploadItem = new UploadItem(fileName, oUrl, tUrl, (byte) 1, null);
} catch (Exception e) {
e.printStackTrace();
uploadItem = new UploadItem(fileName, null, (byte) 0, e.getMessage());
}
images.add(uploadItem);
} else {//其他
try {
uploadItem = new UploadItem(fileName, oUrl, tUrl, (byte) 1, null);
if ((fileName.indexOf(".amr") != -1) && 1 == getSystemConfig().getAmr2mp3()) {
/*File __source = new File(oFile.getPath());
File __target = new File(oFile.getPath().replaceAll(".amr", ".mp3"));
Amr2mp3.changeToMp3(__source.getPath(), __target.getPath());
successCount++;
oUrl= SystemConfig.getUrl(__target);
uploadItem = new UploadItem(__target.getName(),oUrl, (byte) 1, null);*/
} else {
/*successCount++;
oUrl= SystemConfig.getUrl(oFile);
uploadItem = new UploadItem(oFileName, oUrl, (byte) 1, null);*/
}
} catch (Exception e) {
e.printStackTrace();
uploadItem = new UploadItem(fileName, null, (byte) 0, e.getMessage());
}
if (FileType.Audio == fileType)
audios.add(uploadItem);
else if (FileType.Video == fileType)
videos.add(uploadItem);
else
others.add(uploadItem);
}
}

Map<String, Object> data = new HashMap<String, Object>();
data.put("images", images);
data.put("audios", audios);
data.put("videos", videos);
data.put("others", others);


message = new JMessage(1, null, data);

message.put("success", successCount);

return message;
}

protected JMessage defHander(List<FileItem> multipart, long userId, double validTime) {
JMessage jMessage = null;
int successCount = 0;
String oUrl = null;
String tUrl = null;
List<UploadItem> images = Lists.newArrayList();
List<UploadItem> audios = Lists.newArrayList();
List<UploadItem> videos = Lists.newArrayList();
List<UploadItem> others = Lists.newArrayList();

for (FileItem item : multipart) {
UploadItem uploadItem;
if (item.isFormField() || item.getSize() < 1)
continue;
String oFileName = item.getName();
String formatName = ConfigUtils.getFormatName(oFileName);
String newFileName = ConfigUtils.getName(oFileName);
String fileName = null;
if (!StringUtils.isEmpty(newFileName) && !newFileName.equals(oFileName)) {
fileName = 32 == newFileName.length() ? oFileName
: Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);
} else {
fileName = oFileName;
}
/*String fileName = 32 == ConfigUtils.getName(oFileName).length() ? oFileName : Joiner.on("").join(UUID.randomUUID().toString().replace("-", ""), ".", formatName);*/
FileType fileType = getFileType(formatName);
File[] uploadPath = ConfigUtils.getUploadPath(userId, fileType);
if (FileType.Image == fileType) {//图片
File oFile = new File(uploadPath[0], fileName);
File tFile = new File(uploadPath[1], fileName);
try {
FileUtils.transfer(item.getInputStream(), oFile, tFile, formatName);

successCount++;
oUrl = getUrl(oFile);
tUrl = getUrl(tFile);
ResourcesDBUtils.saveFileUrl(1, oUrl, validTime);
ResourcesDBUtils.saveFileUrl(1, tUrl, validTime);
log("UploadServlet uploadEd " + oUrl);
log("UploadServlet uploadEd " + tUrl);
uploadItem = new UploadItem(oFileName, oUrl, tUrl, (byte) 1, null);
} catch (Exception e) {
e.printStackTrace();
uploadItem = new UploadItem(oFileName, null, (byte) 0, e.getMessage());
}
images.add(uploadItem);
} else {//其他
File oFile = new File(uploadPath[0], fileName);
try {
FileUtils.transfer(item.getInputStream(), oFile);
if ((fileName.indexOf(".amr") != -1) && 1 == getSystemConfig().getAmr2mp3()) {
File __source = new File(oFile.getPath());
File __target = new File(oFile.getPath().replaceAll(".amr", ".mp3"));
Amr2mp3.changeToMp3(__source.getPath(), __target.getPath());
successCount++;
oUrl = getUrl(__target);
uploadItem = new UploadItem(__target.getName(), oUrl, (byte) 1, null);
} else {
successCount++;
oUrl = getUrl(oFile);
uploadItem = new UploadItem(oFileName, oUrl, (byte) 1, null);
}
ResourcesDBUtils.saveFileUrl(1, oUrl, -1);
log("UploadServlet uploadEd " + oUrl);
} catch (Exception e) {
e.printStackTrace();
uploadItem = new UploadItem(oFileName, null, (byte) 0, e.getMessage());
}
if (FileType.Audio == fileType)
audios.add(uploadItem);
else if (FileType.Video == fileType)
videos.add(uploadItem);
else
others.add(uploadItem);
}
}

Map<String, Object> data = new HashMap<String, Object>();
data.put("images", images);
data.put("audios", audios);
data.put("videos", videos);
data.put("others", others);
jMessage = new JMessage(1, null, data);

jMessage.put("success", successCount);
return jMessage;

}
}
posted @ 2019-07-15 12:13  EchoDuangDuang~  阅读(806)  评论(0编辑  收藏  举报