- js
$(function() {
function findSize(field_id) {
let fileInput = $("#"+field_id)[0];
let byteSize = fileInput.files[0].size;
return ( Math.ceil(byteSize / 1024 / 1024) );
}
$("#upload-img").click(function () {
if (!$("#show-img").prop("src")) {
return;
}
let imgSize = findSize("upload-input");
if (imgSize >= 2) {
alert('请选择2MB以下的图片');
return;
}
let formData = new FormData($("#img-form")[0]);
$.ajax({
url: "/WebMusicPlayer/uploadFile",
data: formData,
type: "post",
cache: false,
processData: false,
contentType: false,
success: function (img_name) {
$("#music-list-img").val(img_name);
$("#list-img").css('display', 'inline');
$("#list-img").prop('src', $("#show-img").prop('src'));
$("#upd-img").modal('hide');
},
error: function (e) {
console.log(e);
}
});
});
});
- servlet (téléchargement intelligent jsp)
package com.lovely.action;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
@WebServlet(name = "UploadFile", urlPatterns = "/uploadFile")
public class UploadFile extends HttpServlet {
public static String path;
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
SmartUpload su = new SmartUpload();
su.initialize(getServletConfig(), req, resp);
su.setCharset("utf-8");
su.setAllowedFilesList("jpg,png,bmp");
su.setMaxFileSize(1024*1024*2);
try {
su.upload();
System.out.println("用户名:"+su.getRequest().getParameter("userName"));
Files files = su.getFiles();
com.jspsmart.upload.File f = files.getFile(0);
String filePath = getServletContext().getRealPath("/music-manage/img");
System.out.println("项目根路径:"+filePath);
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
String fileName = UUID.randomUUID()+"."+f.getFileExt();
filePath = filePath+"/"+ fileName;
f.saveAs(filePath);
System.out.println("上传成功");
resp.setContentType("text/plain;charset=utf-8");
PrintWriter out = resp.getWriter();
out.print(fileName);
out.close();
} catch (SmartUploadException e) {
e.printStackTrace();
System.out.println("文件上传失败");
}
}
}