gpt4 book ai didi

java - 如何将jsp中multipart/form-data的输入值传递到servlet?

转载 作者:行者123 更新时间:2023-12-02 13:30:58 24 4
gpt4 key购买 nike

我知道这可能是一个重复的问题,我在互联网上读过类似的帖子,但我无法将我的输入值从 jsp 发送到 servlet。我可以上传文件,但我需要发送输入值。小服务程序:

try {
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();


if (item.isFormField()) {
out.println("Got a form field: " + item.getFieldName());


} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

out.println("--------------");
out.println("fileName = " + fileName);
out.println("Kind = " + fileNameWithOutExt);
out.println("field name = " + fieldName);
out.println("contentType = " + contentType);

String fileContents = null;
try {

fileContents = IOUtils.toString(in);
out.println("lenght: " + fileContents.length());

String[] content = fileContents.split("\n");


String[] property = content[0].split(",");

out.println("lunghezza " + property.length);
for (String propr : property) {
out.println("prop: " + propr);
}
//out.println(Arrays.toString(property));
//out.println(fileContents);
} finally {
IOUtils.closeQuietly(in);
}

}
}
} catch (SizeLimitExceededException e) {
out.println("You exceeded the maximu size ("
+ e.getPermittedSize() + ") of the file ("
+ e.getActualSize() + ")");
}
} catch (Exception ex) {

throw new ServletException(ex);
}
}

这就是我的jsp

    <form action="/upload_kind" method="post"  enctype="multipart/form-data" >
<input type="file" name="file" size="50" />
<input type="text" name="namespace" id="namespace">
<br />
<input type="submit" value="Upload File" />
</form>

我读到了有关“item.getString()”方法的信息,但它位于 DiskFileItem 类中,而不是 FileItemStream 中,因此我可以看到“命名空间”已发送,但我看不到它的值。谢谢,抱歉我的英语不好

最佳答案

按照重复的链接,我能够解决我的问题。我使用了这段代码:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}

// ...
}

关于java - 如何将jsp中multipart/form-data的输入值传递到servlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43183986/

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