简单文件服务器和客户端


         

很多的web项目中都会涉及到用户上传图片然后保存到服务器。如果将图片直接放到项目中会造成一些麻烦:

   1. 打包发布项目时会丢失已上传的图片,

   2. 当图片越来越多时会对性能造成一定的影响

所以,将图片从web项目中分离出来,建立一个独立的图片服务器是很有必要的,下面给一个简单的图片服务器接收图片或其它文件的例子和使用URL上传图片或文件到服务器的例子,支持中文文件名。


服务端:


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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.DefaultFileItemFactory;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

public class FileUpLoadServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 
 private String uploadPath = "E:\\"; // 上传文件的目录
    File tempPathFile;
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  doPost(req, resp);
 }
 @SuppressWarnings("unchecked")
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");   
        response.setContentType("text/html");    
        try  {
         DefaultFileItemFactory factory = new DefaultFileItemFactory();
         factory.setSizeThreshold(10240000); // 设置缓冲区大小,这里是4kb
         factory.setRepository(tempPathFile);// 设置缓冲区目录
         // Create a new file upload handler
         DiskFileUpload upload = new DiskFileUpload(factory);
         // Set overall request size constraint
         upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
         upload.setHeaderEncoding("UTF-8");
         List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
         Iterator<FileItem> i = items.iterator();
         while (i.hasNext()) {
          FileItem fi = (FileItem) i.next();
          String fileName = fi.getName();
          if (fileName != null) {
           File fullFile = new File(fi.getName());
           File savedFile = new File(uploadPath, fullFile.getName());
           fi.write(savedFile);
          }
         }
        } catch (Exception e) {
            // 可以跳转出错页面
            e.printStackTrace();
        }
 }
}("UTF-8");
	        List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
	        Iterator<FileItem> i = items.iterator();
	        while (i.hasNext()) {
	        	FileItem fi = (FileItem) i.next();
		        String fileName = fi.getName();
		        if (fileName != null) {
			        File fullFile = new File(fi.getName());
			        File savedFile = new File(uploadPath, fullFile.getName());
			        fi.write(savedFile);
		        }
	        }
        } catch (Exception e) {
            // 可以跳转出错页面
            e.printStackTrace();
        }
	}
}

客户端:参考了一位网友的例子,不记得是谁了,所以不能标明出处了。

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
 
/**
 * This utility class provides an abstraction layer for sending multipart HTTP
 * POST requests to a web server.
 * @author www.codejava.net
 *
 */
public class MultipartUtility {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;
 
    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;
         
        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";
         
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }
 
    /**
     * Adds a form field to the request
     * @param name field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }
 
    /**
     * Adds a upload file section to the request
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = "test.png";
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();
 
        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();
         
        writer.append(LINE_FEED);
        writer.flush();    
    }
 
    /**
     * Adds a header field to the request.
     * @param name - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }
     
    /**
     * Completes the request and receives response from the server.
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException {
        List<String> response = new ArrayList<String>();
 
        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();
 
        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }
 
        return response;
    }
    
    public static void main(String[] args) throws Exception {
		MultipartUtility multipartUtility = new MultipartUtility("http://localhost:8080/FileUpLoad/upLoad", "UTF-8");
		multipartUtility.addFormField("filename", "test.png");
		multipartUtility.addHeaderField("filename", "test.png");
		File fileToUpload = new File("d:/测试.png");
		multipartUtility.addFilePart("test.png", fileToUpload);
	}
    
}

需要jar包






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值