<body>
<form method="post" action="DemoServlet" enctype="multipart/form-data" name="form1">
<input type="file" name="file" />
Image_Name:<input type="text" name="file"/>
<input type="submit" value="Go"/>
</form>
</body>
这是我的index.jsp 页面。 这个Servlet是DemoServlet,当用户点击提交按钮时,它会转到这里。而在jsp页面中,假设用户给出的Image_Name是IPL,图像的实际名称是funny.jpg,那么在保存图像时,它应该存储为IPL.png,这里我能够使用有趣的.jpg正确上传图像,但我需要将图像保存为index.jsp页面的文本字段中的给定名称
public class DemoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Date date = new Date();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(request);
while (itr.hasNext()) {
FileItemStream item = itr.next();
if (item.isFormField()) {
String fieldname = item.getFieldName();
InputStream is = item.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String value = new String(b);
response.getWriter().println(fieldname + ":" + value + "</br>");
} else {
String TempPath = getServletContext().getRealPath("");
String path = TempPath.substring(0, TempPath.indexOf("build"));
if (FileUpload.processFile(path, item)) {
out.println("File Uploaded on:" + date + "<br>");
response.getWriter().println("Image Upload Successfully");
} else {
response.getWriter().println("Failed.....Try again");
}
}
}
} catch (FileUploadException fue) {
fue.printStackTrace();
}
}
}
}
这是java类
public class FileUpload {
public static boolean processFile(String path, FileItemStream item) {
try {
File f = new File(path + File.separator + "web/images");
if (!f.exists()) {
f.mkdir();
}
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
FileOutputStream fos = new FileOutputStream(savedFile);
InputStream is = item.openStream();
int x = 0;
byte[] b = new byte[1024];
while ((x = is.read(b)) != -1) {
fos.write(b, 0, x);
}
fos.flush();
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
任何人都可以指导我如何动态更改此设置。提前致谢。
最佳答案
我不知道 Servlet 等是如何工作的,但是我可以给你一个你需要做什么的概要。
在 DemoServlet 中,您需要接受 Image_Name 字段的输入,并将其作为 FileUpload 的参数之一
public static boolean processFile(String path, FileItemStream item, String fileName){
//Method Code
}
因为当前您的 processFile 方法正在从 FileItemStream 中获取文件名。您需要将其更改为您的实际文件名
File savedFile = new File(f.getAbsolutePath() + File.separator + item.getName());
至
File savedFile = new File(f.getAbsolutePath() + File.separator + fileName + ".png");
关于java - 如何在上传并保存在文件夹中时使用java更改图像名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23074240/