gpt4 book ai didi

java - 我可以在 jsp 页面中使用与输入类型=文件相同的形式输入类型=文本吗?

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:33 24 4
gpt4 key购买 nike

我的 jsp 页面中有一个表单,其中有一个文本输入和一个文件输入。

<form action="servlet/FileUploadHandler" method="post" class="post" id="profilepost" enctype="multipart/form-data">
<div class="form-group">
<label for="createPost">Photo</label>
<input type="text" name="url" class="form-control" id="inputcomment" placeholder="URL...">
</div>
<div class="form-group">
<label for="exampleInputFile">Upload photo</label>
<input type="file" name="file" id="exampleInputFile">
<button type="submit" class="btn btn-primary">Post</button>
</form>

我使用的servlet如下:

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadHandler extends HttpServlet {
private final String UPLOAD_DIRECTORY = "C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\ismgroup9\\fileUpload";

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
request.setAttribute("photoname", name);
}
}

request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}

}else{
request.setAttribute("message", "Sorry this Servlet only handles file upload request");
}

request.getRequestDispatcher("/uploadfileController.jsp").forward(request, response);

}

}

但这仅适用于照片。我该怎么做才能同时拥有文字和照片?我想将它们插入到我的 mysql 数据库的同一个表中。

最佳答案

试试这个,也许它会帮助你解决你的问题。

for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
request.setAttribute("photoname", name);
}else{
// here get value of other parameter which is not file type
System.out.println(item.getFieldName()+" = "+item.getString());
}
}

关于java - 我可以在 jsp 页面中使用与输入类型=文件相同的形式输入类型=文本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28006812/

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