我创建的小程序在小程序查看器中运行时会将图像文件发送到 servlet。但是当我在浏览器中运行它时,它无法将文件发送到 servlet。
我正在使用 Apache HTTPClient 进行文件上传。我的 servlet 在 servlet 包中的一个测试项目中。那么引用它是否正确"http://localhost:8080//test//testServlet"
。
为了在网页中使用它,我构建了小程序项目并将 jar 文件粘贴到与我的 jsp 文件相同的位置。我的小程序代码
package testing;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
/**
*
* @author Computer
*/
public class Upload extends javax.swing.JApplet {
/** Initializes the applet Upload **/
@Override
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
setSize(300,135);
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
chooser = new javax.swing.JFileChooser();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
table = new javax.swing.JTable();
Upload = new javax.swing.JButton();
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title 1"
}
));
jScrollPane1.setViewportView(table);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
);
Upload.setText("Upload");
Upload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UploadActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(Upload))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Upload)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>
private static String executeRequest(HttpRequestBase requestBase){
String responseString = "" ;
InputStream responseStream = null ;
HttpClient client = new DefaultHttpClient () ;
try{
HttpResponse response = client.execute(requestBase) ;
if (response != null){
HttpEntity responseEntity = response.getEntity() ;
if (responseEntity != null){
responseStream = responseEntity.getContent() ;
if (responseStream != null){
BufferedReader br = new BufferedReader (new InputStreamReader (responseStream)) ;
String responseLine = br.readLine() ;
String tempResponseString = "" ;
while (responseLine != null){
tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
responseLine = br.readLine() ;
}
br.close() ;
if (tempResponseString.length() > 0){
responseString = tempResponseString ;
}
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} //catch (ClientProtocolException e) {
// e.printStackTrace();
//}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (responseStream != null){
try {
responseStream.close() ;
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.getConnectionManager().shutdown() ;
return responseString ;
}
public void executeMultiPartRequest(String urlString, File file) {
HttpClient client = new DefaultHttpClient();
HttpPost postRequest = new HttpPost (urlString) ;
try{
MultipartEntity multiPartEntity = new MultipartEntity () ;
FileBody fileBody = new FileBody(file, "application/octect-stream") ;
multiPartEntity.addPart("attachment", fileBody) ;
postRequest.setEntity(multiPartEntity) ;
HttpResponse response = client.execute(postRequest);
}
catch (Exception ex){
ex.printStackTrace() ;
}
//return executeRequest (postRequest) ;
}
private void UploadActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int value = chooser.showOpenDialog(this);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
if(value == JFileChooser.APPROVE_OPTION)
{
System.out.println("Check");
File file = chooser.getSelectedFile();
String name = file.getName().toLowerCase();
if(name.endsWith(".jpg")||name.endsWith(".bmp")||name.endsWith(".png"))
{
String showpathName = chooser.getSelectedFile().getName();
String absolutePathName = file.getAbsolutePath();
System.out.println("Absolute path is "+absolutePathName);
/***Send For Uploading*****/
executeMultiPartRequest("http://localhost:8080//test//testServlet", file) ;
// System.out.println("Response : "+response);
/***************************/
model.addRow(new Object[]{showpathName});
}
else
{
JOptionPane.showMessageDialog(this,"Incorrect File Format");
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton Upload;
private javax.swing.JFileChooser chooser;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table;
// End of variables declaration
/***************************************************************/
/************Servlet code***************************************/
package servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStr
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
*
* @author Computer
*/
public class testServlet extends HttpServlet {
/**
* 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, FileUploadException {
response.setContentType("text/html;charset=UTF-8");
// PrintWriter out = response.getWriter();
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet testServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet testServlet at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items)
{
String filename = FilenameUtils.getName(item.getName());
System.out.println("Filename "+filename);
FileInputStream fis = (FileInputStream) item.getInputStream();
int len = (int) item.getSize();
System.out.println("inputStream"+fis.available());
OutputStream out = new FileOutputStream(new File("C:\\Users\\Computer\\Desktop\\client\\imagenew1.jpg"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = fis.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
fis.close();
out.flush();
out.close();
System.out.println("New file created!");
}
} finally {
}
}
// <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 {
try {
processRequest(request, response);
} catch (FileUploadException ex) {
Logger.getLogger(testServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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 {
try {
processRequest(request, response);
} catch (FileUploadException ex) {
Logger.getLogger(testServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
}