gpt4 book ai didi

java - 如何将 iputStream 转换为字符串并通过 filemap 获取

转载 作者:行者123 更新时间:2023-11-29 05:11:45 24 4
gpt4 key购买 nike

我正在尝试将多个图像插入数据库。我正在插入与以下类型匹配的图像

我的表:

  `Sno` int(11) NOT NULL AUTO_INCREMENT,
`Class` varchar(45) DEFAULT NULL,
`Subject` varchar(45) DEFAULT NULL,
`CreatedBy` varchar(45) DEFAULT NULL,
`QimgName` varchar(45) DEFAULT NULL,
`Qimg` mediumblob,
`AimgName` varchar(45) DEFAULT NULL,
`Aimg` mediumblob,
PRIMARY KEY (`Sno`)

MyJsp.jsp

<form action="MatchImgTImgUpload" method="post" enctype="multipart/form-data">
<div id="container" >
<div>
<img alt="Image1" id="Image1" src="" width="130px" height="90px"><br><br>
<img alt="Image2" id="Image2" src="" width="130px" height="90px"><br><br>
<img alt="Image3" id="Image3" src="" width="130px" height="90px"><br><br>
<img alt="Image4" id="Image4" src="" width="130px" height="90px"><br><br>
<img alt="Image5" id="Image5" src="" width="130px" height="90px"><br><br>
</div>

<div>
<img alt="Image6" id="Image6" src="" width="130px" height="90px"><br><br>
<img alt="Image7" id="Image7" src="" width="130px" height="90px"><br><br>
<img alt="Image8" id="Image8" src="" width="130px" height="90px"><br><br>
<img alt="Image9" id="Image9" src="" width="130px" height="90px"><br><br>
<img alt="Image10" id="Image10" src="" width="130px" height="90px"><br><br>
</div>

</div>
<input type="file" id="files1" name="files1[]" value="Upload Questions" multiple>
<input type="file" id="files2" name="files2[]" value="Upload Answers" multiple>
<input type="submit" value="AddToDB?">
</form>

MatchImgTImgUpload.java :

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String clas="I",subject="EVS",uid="112";
Connection con = null;
List<String> listGet = new ArrayList<String>();
List<String> listGet2 = new ArrayList<String>();

System.out.println("Entered successfully:");
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
//System.out.println("if0 successfully:");
Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
//System.out.println("if0 successfully:");
if (ServletFileUpload.isMultipartContent(request)) {
//System.out.println("if0 successfully:");
// get the request content and iterate through

try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("selected images :"+items);
if (items != null) {
//System.out.println("if0 successfully:");
final Iterator iter = items.iterator();
while (iter.hasNext()) {
//System.out.println("while successfully:");
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
//System.out.println("if1 successfully:");

// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
System.out.println("else successfully:"+item.getName());
System.out.println("else successfully:"+item.getInputStream());
listGet.add(item.getName());

String val = item.getInputStream().toString();
listGet2.add(val);

}
}
}
}
else
{
System.out.println("else successfully:");
}

try {
//System.out.println("try successfully:");

try {



Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");


Set<String> keySet = fileMap.keySet();
int listgetcount = 0;
int count2 =5;
for (int k=1;k<=5;k++) {
System.out.println("for successfully:");
String sql ="INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)" ;
PreparedStatement statement;

statement = con.prepareStatement(sql);

statement.setString(1, clas);
statement.setString(2, subject);
statement.setString(3, uid);

statement.setString(4, listGet.get(listgetcount));


String getval = listGet2.get(listgetcount);

statement.setBlob(5, fileMap.get(getval));



statement.setString(6, listGet.get(count2));

String getval2 = listGet2.get(count2);
statement.setBlob(7, fileMap.get(getval2));


int row = statement.executeUpdate();

System.out.println("inserted successfully:");
listgetcount = listgetcount+1;
count2=count2+1;
}
listgetcount=0;
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
finally{
try {

con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

它的插入如下,

enter image description here

我正在尝试的是,有 10 张(左侧图像 5 和右侧图像 5)图像,但我必须插入,例如第 1 张图像(左)是问题,第 6 张(右)图像是第 1 张图像的答案想插入第 5 张图片是问题,第 10 张图片是第 5 张图片的答案。从上面的代码中,除了 statement.setBlob(5, fileMap.get(getval));statement.setBlob(7, fileMap.get(getval2)); 因为它的值得到 null 值。

我猜这个问题是因为转换 String val = item.getInputStream().toString();listGet2.add(val); 所以请有人帮助我。

连我都试过了,

statement.setBlob(5, fileMap.get(0));statement.setBlob(7, fileMap.get(5));

但是没有用,希望有人指出我的错误。

更新:

我在这里更新了我的问题取决于下面发布的答案。我尝试了你的代码,即使我卡在了代码中,

private DataSource dataSource;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String clas="I",subject="EVS",uid="112";

List<String> listGet = new ArrayList<String>();

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);

if (!ServletFileUpload.isMultipartContent(request)) {
throw new RuntimeException("..."); // ...or return a HTTP 400
}

// Collecting what's in the request
Map<String, byte[]> contents = new HashMap<String, byte[]>();
List<FileItem> items = fileUpload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
contents.put(item.getFieldName(), item.get());
listGet.add(item.getFieldName());
}
}

try (Connection connection = ((Statement) dataSource).getConnection()) {
try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO tbl_MatchImgToImg (Class, Subject, CreatedBy, QimgName, Qimg, AimgName, Aimg) values (?, ?, ?, ?, ?, ?, ?)")) {
// For this part, you'll need Google Guava - but you can write your own checkNotNull(), too
int answerimgcount = 5;
for(int k=0;k<=4;k++){
byte[] image1 = Preconditions.checkNotNull(contents.get("field1"),
"...error: invalid request, missing field1...");
byte[] image2 = Preconditions.checkNotNull(contents.get("field2"),
"...error: invalid request, missing field2...");
// ...
stmt.setString(1, clas);
stmt.setString(2, subject);
stmt.setString(3, uid);

stmt.setString(4, listGet.get(k));
// ...
stmt.setBytes(5, image1);
// ...
stmt.setString(6, listGet.get(answerimgcount));
stmt.setBytes(7, image2);

answerimgcount =answerimgcount+1;
}
}
}
}

它显示如下图所示的错误,

enter image description here

无论我给出什么修复上面的代码不起作用,所以现在告诉我哪里错了!

即使我简单地尝试过,

List<String> listGet = new ArrayList<String>();

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);

if (!ServletFileUpload.isMultipartContent(request)) {
throw new RuntimeException("..."); // ...or return a HTTP 400
}

// Collecting what's in the request
Map<String, byte[]> contents = new HashMap<String, byte[]>();
List<FileItem> items = null;
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (FileItem item : items) {
if (!item.isFormField()) {
contents.put(item.getName(), item.get());
listGet.add(item.getName());
}
}

int answerimgcount = 5;
for(int k=0;k<=4;k++){
System.out.println("imageName successfully:"+listGet.get(k));
byte[] image1 = contents.get("field1");
System.out.println("image1 successfully:"+image1);
System.out.println("imageName successfully:"+listGet.get(answerimgcount));
byte[] image2 =contents.get("field2");
System.out.println("image1 successfully:"+image2);


answerimgcount =answerimgcount+1;
}

但是 OP :

imageName successfully:image1.jpg
image1 successfully:null
imageName successfully:image6.jpg
image1 successfully:null
imageName successfully:image2.jpg
image1 successfully:null
imageName successfully:image7.jpg
image1 successfully:null
imageName successfully:image3.jpg
image1 successfully:null
imageName successfully:image8.jpg
image1 successfully:null
imageName successfully:image4.jpg
image1 successfully:null
imageName successfully:image9.jpg
image1 successfully:null
imageName successfully:image5.jpg
image1 successfully:null
imageName successfully:image10.jpg
image1 successfully:null
imageName successfully:
image1 successfully:null

最佳答案

我认为项目为 null 是您问题中最少的(实际上只是您的代码过于复杂和困惑的副作用 - 抱歉这么说)。

具体问题:

  • 使用了很多不必要的数据结构(列表和映射)
  • 对这些列表的内容做出大量假设
  • 在应该检查空值时不检查
  • 在不必要时检查空值(如果深入研究,parseRequest() 永远不会返回空值)
  • InputStream.toString() 是错误的...它是一个字节流,您不应该只是将它转换为 Unicode 字符串(特别是因为您将它们作为 blob 存储在数据库中,也是)
  • 不应捕获和忽略导致无法继续处理的错误(FileUploadException)
  • 使用 System.out 而不是日志框架
  • 如果无法建立连接,finally() 将失败并出现 NPE - 如果可以,最好使用 Java7 的 try-with block ,或 Apache Commons 的 IOUtils.closeQuietly()
  • 使用 InputStreams 需要多加注意,因为它们只能被读取一次。我建议改为以 byte[] 形式获取数据(数据库驱动程序可能无论如何都会这样做)。

现在,让我们稍微清理一下:

// This one SHOULD be dependency injected... opening DB connections on your own
// rather than relying on a connection pool will lead to all sorts of problems
private DataSource dataSource;

protected void doPost2(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException, SQLException, FileUploadException {

// I'd rather get these dependency-injected
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);

if (!ServletFileUpload.isMultipartContent(request)) {
throw new RuntimeException("..."); // ...or return a HTTP 400
}

// Collecting what's in the request
Map<String, byte[]> contents = new HashMap<>();
List<FileItem> items = fileUpload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
contents.put(item.getFieldName(), item.get());
}
}

try (Connection connection = dataSource.getConnection()) {
try (PreparedStatement stmt = connection.prepareStatement("...insert sql here...")) {
// For this part, you'll need Google Guava - but you can write your own checkNotNull(), too
byte[] image1 = Preconditions.checkNotNull(contents.get("field1"),
"...error: invalid request, missing field1...");
byte[] image2 = Preconditions.checkNotNull(contents.get("field2"),
"...error: invalid request, missing field2...");
// ...

stmt.setString(1, "...");
// ...
stmt.setBytes(4, image1);
// ...
stmt.setString(6, "...");
stmt.setBytes(7, image2);
}
}
}

关于java - 如何将 iputStream 转换为字符串并通过 filemap 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28190427/

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