gpt4 book ai didi

java - 如何将数据从 servlet 发布到 Javascript 或如何将上传的字节从 servlet 发布到 HTML

转载 作者:行者123 更新时间:2023-12-03 11:12:06 27 4
gpt4 key购买 nike

我想将文件上传到服务器,但我不明白:How post data from servlet to javascipt or how post uploaded bytes to html from servlet.上传文件的类是UploadFileServlet,类在consol-UploadStream和form-uploadFile.html中列出。 UploadStream 将数据打印到控制台,但我想将此数据重定向到 html 形式并打印。

上传流

public static class UploadStream extends FilterOutputStream {

final ProgressListener listener;
private long transferred;
public long bytes;

public UploadStream(final OutputStream out, final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}

public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
bytes = this.transferred += len;
System.out.println(this.transferred / 1024 + " KB");
}

public void write(int b) throws IOException {
out.write(b);
this.transferred++;
}

public void getBytes(HttpServletRequest request) throws ServletException, IOException {
request.setAttribute("bytes", bytes);
}
}

UploadFileServlet

public class UploadFileServlet extends HttpServlet {
private boolean isMultipart;
//Maximum file size, 2gb
private final int maxFileSize = 1024 * 1024 * 2000;
//Maximum memory size, 3gb
private final int maxMemSize = 1024 * 1024 * 3000;
private File fileToSave;

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/html;charset=UTF-8");
isMultipart = ServletFileUpload.isMultipartContent(request);
java.io.PrintWriter out = response.getWriter();
if (!isMultipart) {
out.println("<h1>No file uploaded</h1>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);

try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
fileToSave = new File(this
+ fileName.substring(fileName.lastIndexOf("\\")));
} else {
fileToSave = new File(this
+ fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(fileToSave);
}
}
} catch (Exception ex) {
out.println(ex.getMessage());
}
/* TODO output your page here. You may use following sample code. */
out.println("Image uploaded!");
File file = new File(fileToSave.getAbsoluteFile().toString());
String date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date (System.currentTimeMillis()));
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(getUrl()+"upload.php");
MultipartEntity reqEntity = new MultipartEntity(){
ProgressListener listener;
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new UploadStream(outstream,listener));
}
};
FileInputStream fis = new FileInputStream(file);
autorization(reqEntity,"upload");
reqEntity.addPart("title", new StringBody(date));
reqEntity.addPart("media", new InputStreamBody(fis, file.toString()));
post.setEntity(reqEntity);
HttpResponse httpResponse = client.execute(post);
HttpEntity resEntity = httpResponse.getEntity();
InputStream inputStream = resEntity.getContent();
String resultString = ProjectLibrary.convertStreamToString(inputStream);
//request.setAttribute("bytes", "");
String url = "/WEB-INF/jsp/resultsUploadFile.jsp";
request.getRequestDispatcher(url).forward(request, response);
file.delete();
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

HTML:

<!DOCTYPE HTML>
<html>
<head>
<title>Multiple file uploader</title>
<script>
var totalFileLength, totalUploaded, fileCount, filesUploaded;

function debug(s) {
var debug = document.getElementById('debug');
if (debug) {
debug.innerHTML = debug.innerHTML + '<br/>' + s;
}
}

function onUploadComplete(e) {
totalUploaded += document.getElementById('files').
files[filesUploaded].size;
filesUploaded++;
debug('complete ' + filesUploaded + " of " + fileCount);
debug('totalUploaded: ' + totalUploaded);
if (filesUploaded < fileCount) {
uploadNext();
} else {
alert('Finished uploading file(s)');
}
}

function onFileSelect(e) {
var files = e.target.files; // FileList object
var output = [];
fileCount = files.length;
totalFileLength = 0;
for (var i = 0; i < fileCount; i++) {
var file = files[i];
output.push(file.name, ' (',
file.size, ' bytes, ',
file.lastModifiedDate.toLocaleDateString(), ')'
);
output.push('<br/>');
debug('add ' + file.size);
totalFileLength += file.size;
}
document.getElementById('selectedFiles').innerHTML =
output.join('');
debug('totalFileLength:' + totalFileLength);
}

function onUploadProgress(e) {
if (e.lengthComputable) {
var percentComplete = parseInt(
(e.loaded + totalUploaded) * 100
/ totalFileLength);
var bar = document.getElementById('bar');
bar.style.width = percentComplete + '%';
bar.innerHTML = percentComplete + ' % complete';
} else {
debug('unable to compute');
}
}

function onUploadFailed(e) {
alert("Error uploading file:" + e);
}

function uploadNext() {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = document.getElementById('files').files[filesUploaded];
fd.append('media', file);
xhr.upload.addEventListener("progress", onUploadProgress, false);
xhr.addEventListener("load", onUploadComplete, false);
xhr.addEventListener("error", onUploadFailed, false);
debug('uploading ' + file.name);
xhr.open('POST', 'UploadFileServlet', true);
xhr.send(fd);
}

function startUpload() {
totalUploaded = filesUploaded = 0;
uploadNext();
}
window.onload = function () {
document.getElementById('files').addEventListener(
'change', onFileSelect, false);
document.getElementById('uploadButton').
addEventListener('click', startUpload, false);
}

</script>
</head>
<body>
<h1>Multiple file uploader</h1>
<div id='progressBar' style='height:20px;border:2px solid green'>
<div id='bar'
style='height:100%;background:#33dd33;width:0%'>
</div>
</div>
<form id='form1' action="UploadFileServlet"
enctype="multipart/form-data" method="post">
<input type="file" id="files" multiple/>
<br/>
<output id="selectedFiles"></output>
<input id="uploadButton" type="submit" value="Upload"/>
</form>
<div id='debug'
style='height:100px;border:2px solid green;overflow:auto'>
</div>
</body>
</html>

最佳答案

通常,Web 应用程序(或网页)与 servlet 之间的通信将在两端实现。

jQuery 有许多有用的 API 文档,可用于对后端的许多调用。主要是POST并且将进行 GET 调用。您可以找到API here 。您需要确定要与之通信的 servlet,文档应为此提供足够的解释。

然后对于 servlet,您需要实现一种方法来检索 POST/GET 调用。您上面创建的 servlet 看起来很可靠。只需给它一个唯一的标识符,以便来自前端的任何调用都可以针对该不同的类。

类似的东西

@WebServlet("UploadServlet")
public class UploadFileServlet extends HttpServlet {

我相信您只需要更新 HTML/Javascript。查看 jQuery 的 API,您应该能够掌握它。

我建议您正确转换文件后,将其包含在 JSON 格式中(即:var json = {}; json.section = "example";),以便您可以传递附加数据。但主要是 JSON 是前端和后端之间发送数据最常用的格式。

JSON 格式如下所示:

{部分:“示例”}

您可以根据需要在 JSON 中添加任意数量的参数。只要确保没有添加任何不需要的内容即可。最好保持 JSON 的大小尽可能小。但有时这是无法避免的。

我使用 ajax 调用将文件发送到 servlet。

例如,它看起来像这样:

$.ajax({
type: "POST",
url: "UploadServlet",
data: { fileContents: fileVariable }
});

您可以在 JavaScript 中轻松创建 JSON:

var json = {};
json.fileContents = convertFile;

然后你只需将 ajax 调用更新为

$.ajax({
type: "POST",
url: "UploadServlet",
data: json
});

这不是一个完整的解决方案,但我相信它解决了我看到的一些问题。

关于java - 如何将数据从 servlet 发布到 Javascript 或如何将上传的字节从 servlet 发布到 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27531810/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com